[CALUG] Shell script question.
Jim Bauer
jfbauer at comcast.net
Wed Mar 3 18:00:47 EST 2010
Brian Debelius wrote:
> Hi,
>
> Looking at Bacula scripts and other scripts, I see a test for an
> empty string performed by adding an 'x' before the variable, and then
> comparing this to another string that is just an 'x'.
>
> The shell test function has a -z string test that returns true if the
> string is empty.
>
> It appears to me that more people use the 'x' comparison. Is there a
> technical reason why one would be preferable to the other?
>
> Why would you do this:
>
> if [ "x$var" = "x" ]; then
> ...
> fi
>
> Instead of this:
>
> if [ -z $var ]; then
> ...
> fi
To protect against an error if var was something like '-a'. Most modern
shells don't get tripped up over things like that. But older systems
would generate an error.
And your -z version above has a bug. Try it with var="a b".
Use "$var" not $var to fix it.
More information about the CALUG
mailing list