bash:基本的 if 条件不起作用? (字符串比较)

bash: elementary if-conditions not working? (string comparison)

当我 运行 这个脚本在 bash:

#!/bin/bash

str="no"

if [ "$str"="yes" ]; then
    echo "condition 1 is true"
fi

if [ "$str"=="yes" ]; then
    echo "condition 2 is true"
fi

if [[ "$str"="yes" ]]; then
    echo "condition 3 is true"
fi

if [[ "$str"=="yes" ]]; then
    echo "condition 4 is true"
fi

if (( "$str"="yes" )); then
    echo "condition 5 is true"
fi

if (( "$str"=="yes" )); then
    echo "condition 6 is true"
fi

令我惊讶的是,我得到:

condition 1 is true
condition 2 is true
condition 3 is true
condition 4 is true
condition 5 is true
condition 6 is true

请注意 $str 设置为 no,而不是 yes

我不完全理解 === 之间的区别(至少,不是在这个 bash 上下文中,我在其他语言中理解)或者把 if条件单 [ ... ] 或双 [[ ... ]] 或双 (( ... )) 括号。

不过我这里明明是哪里出了问题,就是看不出来?

您需要用空格分隔等号。例如:

#!/bin/bash

str="no"

if [ "$str" = "yes" ]; then
    echo "condition 1 is true"
fi

...

首先,运算符周围没有空格,您实际上是在测试(例如)

[ "no=yes" ]

这将评估为真(非空字符串)。

[...] 正在使用 [ 外部测试命令(大概是 /bin/[)进行测试,而 [[...]] 是 shell(bash 或 ksh实例)内置测试。对于测试 === 具有相同的含义。在内置测试 ([[...]]) 的情况下,实际上是针对模式匹配进行评估的:即 [[ yeees == y*s ]] 也是如此。

((...))是算术求值。 = 是赋值,== 测试相等性。在我的例子中(可以归结为 bash 版本)#5 实际上产生 false 除非我事先设置 yes=1 作为评估 return 值分配...在这种情况下新变量命名no 因为那是 str 指向(已解决)的内容。对于比较,如果两个变量的值相等,则此算术比较将 return 为真...字面意思是 (( no == yes )) 或在测试语法中 [[ "$no" -eq "$yes" ]]。如果既没有设置 no 也没有设置 yes,则比较两个 0。