Your shell script question answered

D. Curtis Willoughby ka0vba at dimcom.net
Thu Mar 29 23:00:04 EDT 2012


Hi Greg

Others have told you other ways to skin the cat.  I will try to explain
why what you did did what it did, and suggest a way to make what
you did work.

I have to say, your script is a little strange, but I assume you did it to
illustrate something which you are doing in another script.

The true command produces no output on standard out, but only
returns an exit status of zero.

Since its exit status is zero, the "echo $?" after the || is
not evaluated.  (not executed)

Thus there is no output from the command(s) between the grave accent (`)
characters.

When the shell evaluates the null string standing alone, it is
treated as nothing at all, and thus the first non-blank character
after the open bracket ([) is the equal sign (=).  Your error message
is a complaint from the shell that an equal sign is not allowed
as the first character inside an open bracket.

When I run your script fragment, i get:

unary operator expected

which means the same thing.

If you want the shell to see that null string as a separate string,
you must enclose it in quotation marks like this:

if [ "`/bin/true || echo $?`" = 1 ] ; then
echo "returned 1"
fi

which does in fact produce no output.

Of course, if you want the script to tell the truth, you should
do this:

if [ "`/bin/true || echo $?`" = 1 ] ; then
echo "returned 0" i.e. true
else
echo "returned 1" i.e. false
fi

The zero from the true command is in fact not equal to 1.

I hope this is more informative than confusing.

D. Curtis Willoughby

On Wed, 28 Mar 2012 23:45:17 -0700
Gregory Nowak <greg at romuald.net.eu.org> wrote:
Subject: ot, bash programming question

> Hi folks,
> 
> apologies for the off topic post, but I'm hoping someone can answer my
> question.
> 
> In a bash script, how do you deal with a program returning 0 in an if
> statement?
> Here's a script to illustrate what I mean
> 
> #!/bin/sh
> if [ `/bin/true || echo $?` = 1 ] ; then
> echo "returned 1"
> fi
>  
> When I run this, I should just get the bash prompt back. When I run it
> though, I get:
> 
> [: 4: =: unexpected operator
> 
> followed by the prompt.
> I understand this happens because true exits with 0 status, and it
> isn't echoed back, so the if statement compares nothing to 1. What I'd
> like to know is how to get around that? Thanks in advance.
> 
> Greg
> 
> 
> - -- 
> web site: http://www.romuald.net.eu.org
> gpg public key: http://www.romuald.net.eu.org/pubkey.asc
> skype: gregn1
> (authorization required, add me to your contacts list first)
> 
> - --
> Free domains: http://www.eu.org/ or mail dns-manager at EU.org
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.10 (GNU/Linux)
> 
> iEYEARECAAYFAk90BP0ACgkQ7s9z/XlyUyCQGACgxxLgwZEYcu5pvsscH4wVpBTH
> JrQAnAyQjTipfY5mHCExzyq552b7n8Fc
> =FT/Z
> -----END PGP SIGNATURE-----
> 




More information about the Speakup mailing list