使用引号

使用引号
$ [ $(echo) = $(echo) ]
$ echo $?
0
$ [ $(echo) != $(echo) ]
$ echo $?
0

这是一个错误吗?

PS我在尝试测试字符串是否为空时注意到了这一点;看来我可以将其用于test -z此目的,但我仍然对此感到好奇。

答案1

这不是一个错误。

您没有引用命令替换,因此它被扩展为空(而不是保留为空字符串)。运行的测试实际上是:

[ = ]
[ != ]

使用单个参数,[ ]测试参数是否不是空字符串,并且实际上也不=!=空字符串。

使用引号

(除非您需要非引用扩展的效果,但您可能不需要)

[ "$(echo)" = "" ] # $? = 0
[ "$(echo)" != "" ] # $? = 1

答案2

当你这样做[ $(echo) != $(echo) ] 不引用,相当于[ != ]

现在,测试的行为取决于参数的数量,如下man bash所示:SHELL BUILTIN COMMANDS[ ... ]

          0 arguments
                 The expression is false.
          1 argument
                 The expression is true if and only if the argument is not null.

因此细绳 !=不为空,则测试为TRUE

如果你引用这些参数,你将得到预期的行为:

$ [ "$(echo)" != "$(echo)" ]
$ echo $?
1
$ [ "$(echo)" = "$(echo)" ]
$ echo $?
0

因为你现在给了它 3 个参数:

  3 arguments
         The following conditions are applied in the order listed.
         If the second argument is one of the  binary  conditional
         operators listed above under CONDITIONAL EXPRESSIONS, the
         result of the expression is the result of the binary test
         using  the first and third arguments as operands.  The -a
         and -o operators are  considered  binary  operators  when
         there  are  three arguments.  If the first argument is !,
         the value is the negation of the two-argument test  using
         the second and third arguments.  If the first argument is
         exactly ( and the third argument is exactly ), the result
         is  the one-argument test of the second argument.  Other‐
         wise, the expression is false.

相关内容