为什么两个空字符串比较不相等?

Why do two empty strings compare as not equal?

my@comp:~/wtfdir$ cat wtf.sh
str1=$(echo "")
str2=$(echo "")

if [ $str1 != $str2 ]; then
  echo "WTF?!?!"
fi
my@comp:~/wtfdir$ ./wtf.sh
WTF?!?!
my@comp:~/wtfdir$

这是怎么回事?!

我是如何写上面的代码的:谷歌搜索 "bash compare strings" 把我带到 this website 上面说:

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!=” is used to check inequality of the strings.

但我得到了以上信息?

我有什么不明白的?我做错了什么?

你根本不是 运行 比较,因为你没有在必须使用引号的地方使用引号。请参阅来自 http://shellcheck.net/ about unquoted expansions at SC2086 的警告。

如果两个字符串都为空,则:

[ $str1 != $str2 ]

...评估为...

[ != ]

...这是对字符串 != 是否为非空的测试,为真。将您的代码更改为:

[ "$str1" != "$str2" ]

...这些字符串的确切值实际上将传递给 the [ command.


另一种选择是使用 [[;如 BashFAQ #31 and the conditional expression page on the bash-hackers' wiki 中所述,这是扩展的 shell 语法(在 ksh、bash 和其他扩展 POSIX sh 标准的常见 shell 中),它抑制了令您不快的字符串拆分行为:

[[ $str1 != "$str2" ]]

...仅在右侧需要引号,即使是空字符串情况也不需要引号,但要防止右侧被视为 glob(导致比较如果 str2='*').

始终反映匹配