Reputation: 189
I was wondering how comes
test -n
return 'true', for example :
if test -n; then echo "yes" ; else echo "no" ; fi
prints "yes", even though test was given, theoretically, an empty-length string as an argument along with the option -n, which checks whether the string length is 0 (returns false) or something else (returns true).
Thank you
Upvotes: 4
Views: 5586
Reputation: 45
Let's be more specific. Consider this script:
if [ -n $myvar ]
then
echo true
else
echo false
Notice that myvar is not defined. The script prints "true", which is not expected. Now change $myvar to "$myvar". The script prints "false", which makes sense. Notice also that
test $myvar
also prints false, as expected. This difference is not explained anywhere in the bash docs or numerous SO posts on this observation. The quotes are supposed to make bash treat the variable contents as a single string, but that is not applicable here. Any help, please.
Upvotes: 0
Reputation: 74800
From the documentation:
The
test
and[
builtins evaluate conditional expressions using a set of rules based on the number of arguments.0 arguments: The expression is false.
1 argument: The expression is true if and only if the argument is not null.
In your case you simply have one non-null argument (-n
).
Upvotes: 5
Reputation: 754560
It returns true for the same reason test x
returns true - the string -n
is non-empty. It is not exercising the -n
option because -n
requires a second argument and you've not provided one.
test -n "" || echo false
x=""
test -n $x && echo true
test -n "$x" || echo false
Each echo command is executed; note, in particular, the middle one!
Upvotes: 3