( test -n $st ) != ( test -z $st ) right?

As I read,

test -n $string ==> Exit status is 0 if $string is not null, 1 otherwise

and

test -z $string ==> Exit status is 0 if $string is null, 1 otherwise

But in this particular example, (I tried to create a null string) it seems I am missing some thing.

#!/bin/sh
str=""
test -n $str
echo $?
test -z $str
echo $?

Output of this is:

0
0

enter image description here

Can anyone give an explanation for this strange behavior??

Answer

Put $str inside double quotes!

The -n test requires that the string be quoted within the test brackets. Using an unquoted string with ! -z, or even just the unquoted string alone within test brackets (see Example 7-6) normally works, however, this is an unsafe practice. Always quote a tested string. Other Comparison Operators

Leave a Reply

Your email address will not be published. Required fields are marked *