Bash if 语句给出与预期相反的响应
Bash if statement gives opposite response than expected
我想我遗漏了一些非常明显的东西。但是下面的代码不应该产生相反的响应吗?我认为如果使用语句 "if s == d" 并且 s 不等于 d 那么 if 语句应该 return false 而不是 运行 下面的代码。这不是看起来发生的事情。谁能解释我错过了什么。我认为这是非常明显的事情。
谢谢
s=2
d=3
if ! [ "$s == $d" ]; then echo "hello"; fi
if [ "$s == $d" ]; then echo "hello"; fi
hello
当您应该引用两个参数 "$s"
和 "$d"
时,您引用了整个字符串 "$s == $d"
。
这意味着您不是将 $s
与 $d
进行比较,而是检查 "2 == 3"
是否为非空字符串(它是)。
这将正确打印 "not equal":
s=2
d=3
if ! [ "$s" == "$d" ]; then echo "not equal"; fi
if [ "$s" == "$d" ]; then echo "equal"; fi
我想我遗漏了一些非常明显的东西。但是下面的代码不应该产生相反的响应吗?我认为如果使用语句 "if s == d" 并且 s 不等于 d 那么 if 语句应该 return false 而不是 运行 下面的代码。这不是看起来发生的事情。谁能解释我错过了什么。我认为这是非常明显的事情。
谢谢
s=2
d=3
if ! [ "$s == $d" ]; then echo "hello"; fi
if [ "$s == $d" ]; then echo "hello"; fi
hello
当您应该引用两个参数 "$s"
和 "$d"
时,您引用了整个字符串 "$s == $d"
。
这意味着您不是将 $s
与 $d
进行比较,而是检查 "2 == 3"
是否为非空字符串(它是)。
这将正确打印 "not equal":
s=2
d=3
if ! [ "$s" == "$d" ]; then echo "not equal"; fi
if [ "$s" == "$d" ]; then echo "equal"; fi