I know i can test a string whether it is empty with -z and test a string whether it is non empty with -n. So I write a script in ubuntu 10.10:
#!/bin/bash
A=
test -z $A && echo "A is empty"
test -n $A && echo "A is non empty"
test $A && echo "A is non empty"
str=""
test -z $str && echo "str is empty"
test -n $str && echo "str is non empty"
test $str && echo "str is non empty"
To my surprise, it output :
A is empty
A is non empty
str is empty
str is non empty
which I thing it should be
A is empty
str is empty
Could any Linux expert explain why ?
Thank you.
This is a consequence of the way Bash command lines are parsed. Variable substitution happens before constructing the (rudimentary) syntax tree, so the -n operator doesn't get an empty string as an argument, it gets no argument at all! In general, you must enclose any variable reference into "" unless you can be positively sure it isn't empty, precisely to avoid this and similar problems
The 'problem' comes from this:
$ test -n && echo "Oh, this is echoed."
Oh, this is echoed.
i.e. test -n without an argument returns 0/ok.
Change that to:
$ test -n "$A" && echo "A is non empty"
and you'll get the result you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With