开发者

Why does 'test -n' return 'true' in bash?

I was wondering how comes

test -n

return 'true', for example :

if test -n; then echo "开发者_JAVA百科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


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).


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜