开发者

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

开发者 https://www.devze.com 2023-02-19 21:37 出处:网络
I was wondering how comes test -n return \'true\', for example : if test -n; then echo \"开发者_JAVA百科yes\" ; else echo \"no\" ; fi

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

精彩评论

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

关注公众号