To what value does an unquoted, undeclared variable expand to in order to return an exit status of 0
?
Here is an example of a particular situation I ran into:
[ -n $var ]; echo $?
0
[ -n "$var" ]; echo $?
1
In both tests, the variable var
is not declared.
I could have saved me the hassle by testing with -z
, where quoted or unquoted apparently doesn't make a difference, but I ran into this particular situation and I started wondering. I looked deeper into all the expansions that bash performs, but couldn't find any explanation for this behavior.
As a general rule I usually quote variables, but hopefully the reason of this behavior helps me better understand quoting.
[ -n ]
is true (0) since-n
is a non-empty string. Also note that[ -z $var ]
would have been true for the same reason. I suspect there would be a duplicate question for this somewhere... – Kusalananda Oct 21 '20 at 12:03-n
:[ "$var" ]
or[ $var ]
– nezabudka Oct 21 '20 at 12:17[ $var ]
, it breaks the moment$var
contains more than one word – ilkkachu Oct 21 '20 at 13:22[ -z $var ]
works quoted or not as long as$var
contains one or zero words. I think there was a post explaining that somewhere, but I can't find it so I'll leave this as an exercise... – ilkkachu Oct 21 '20 at 13:24[ -n $var ]
or[ -z $var ]
. "In your case...". Considering a certain example. – nezabudka Oct 21 '20 at 13:39