Home > Blockchain >  Understanding bash's 'test -z' vs 'test -n'
Understanding bash's 'test -z' vs 'test -n'

Time:11-13

I think I understand -z. If a variable is empty test will return true. But I don't understand -n. man test tells me:

     -n string     True if the length of string is nonzero.

So I execute these command lines:

bash-3.2$ thing=abc
bash-3.2$ test -z $thing && echo "x${thing}x"
bash-3.2$ test -n $thing && echo "x${thing}x"
xabcx
bash-3.2$ thing=""
bash-3.2$ test -z $thing && echo "x${thing}x"
xx
bash-3.2$ test -n $thing && echo "x${thing}x"
xx

Why does test -n $thing && echo "x${thing}x" output xx? Doesn't $thing have a length of zero? Shouldn't test -n $thing have returned false?

CodePudding user response:

$thing is null, so as soon as it gets dereferenced, it stops existing on the command line, and so it never gets delivered as an argument to test.

To fix this, quote it:

$ test -n "$thing" && echo "x${thing}x"
$ 

See When should I wrap quotes around a shell variable?


Or, a better solution is to avoid test and [ ] altogether, and use [[ ]] instead.

$ [[ -n $thing ]] && echo "x${thing}x"
$

See Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

  •  Tags:  
  • bash
  • Related