BASH:[](测试)表现不一致

时间:2011-10-25 13:29:04

标签: linux bash gnu

在我的bash中test有退出状态0的态度:

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

,而

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

这意味着当它根本没有收到任何参数时,它会假定为非零。

案例-z正常运作:

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

这是预期的行为吗?

3 个答案:

答案 0 :(得分:6)

基本上,您要测试字符串“-z”是否为非空。它是,所以它告诉你true。实际算法测试使用的是:

  
      
  • 0个参数:

         

    退出false(1)。

  •   
  • 1个论点:

         

    如果$ 1不为null,则退出true(0);否则,退出false。

  •   
  • 2个论点:

         

    如果$ 1是'!',如果$ 2为null,则返回true;如果$ 2不为null,则返回false。

         

    如果$ 1是一元主要,如果一元测试为真,则返回true,false   如果一元测试是假的。

         

    否则,产生未指定的结果。

  •   
     

...

引自the POSIX test command specification

答案 1 :(得分:1)

据推测,没有参数“-n”和“-z”不被视为运算符,而仅仅是字符串,test "a non-empty string"是真的。我猜想test将其参数作为第一步计算,如果计数为1,则只需检查参数的长度。

答案 2 :(得分:0)

是的,这是预期的。

$ 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会返回所有选项的退出状态。

试试这些:

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