BASH: [ ] (test) behaves unconformly

被刻印的时光 ゝ 提交于 2019-12-10 14:08:20

问题


In my bash test has an attitude to exit with status 0:

$ test -n && echo true || echo false
-> true

while

$ test -n "" && echo true || echo false
-> false

It means when it doesn't receive any argument at all, it assumes nonzero.

The case -z works properly instead:

$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true

Is this the expected behavior?


回答1:


Basically, you are asking test whether the string "-z" is nonempty. It is, so it tells you true. The actual algorithm test uses is:

  • 0 arguments:

    Exit false (1).

  • 1 argument:

    Exit true (0) if $1 is not null; otherwise, exit false.

  • 2 arguments:

    If $1 is '!', exit true if $2 is null, false if $2 is not null.

    If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.

    Otherwise, produce unspecified results.

...

Quoted from the POSIX test command specification.




回答2:


Presumably, without arguments "-n" and "-z" are not treated as operators but as mere strings, and test "a non-empty string" is true. I would guess that test counts its arguments as a first step, and if the count is 1, simply examine the length of the argument.




回答3:


Yes it is expected.

$ man test
-n string                   True if the length of string  is
                             non-zero.
-z string                   True if  the  length  of  string
                             string is zero.

test [option] #without any operand returns an exit status that is true for ALL options.

Try these:

test -d
test -f
test -n
test -G
test -k
...


来源:https://stackoverflow.com/questions/7890017/bash-test-behaves-unconformly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!