Wednesday, February 17, 2010

Stupid bash tricks: when is a null string not a null string?

I've done this more than once, and it still seems to me there ought to be an error.

The 'test' command says:

      -n STRING
              the length of STRING is nonzero

       STRING equivalent to -n STRING

       -z STRING
              the length of STRING is zero

 So something like this should work:

$ /home/tim>TEST=""
$ /home/tim>if test -z $TEST; then echo "null"; else echo "not null";fi
null

and it does.   But this should not work:

$ /home/tim>if test -n $TEST; then echo "not null"; else echo "null";fi  
not null

Hang on.  It can't be both!  Let's check out the length:

$ /home/tim>expr length $TEST
expr: syntax error

Huh?  How about feeding it a real string:

$ /home/tim>expr length "" 
0

Here's the problem.   Absent quotes around the $TEST, expr sees this as a command missing a parameter.  So this works just fine:

$ /home/tim>expr length "$TEST"
0

as does this:

$ /home/tim>if test -n "$TEST"; then echo "not null"; else echo "null";fi
null

So sometimes putting quotes around a string variable does make a difference...

No comments:

Post a Comment