3

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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

2

This one will work:

#!/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"

Just $A or $str as empty string will not be a parameter for test and then test status is always true with one parameter (string with nonzero length). The last line works right because test without parameters returns always false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.