bash if语句在控制台中出现语法错误,但工作正常

时间:2017-11-29 01:58:00

标签: bash shell if-statement

使用bash if语句检查两个不同数组中的两个数字是否相等。似乎在语句应该评估为false的情况下(即两个数字不相等),控制台会显示语法错误。

有问题的代码:

for((i=0;i<=passes256Size;i+=1));do
    if((${passes212[$i]}==${passes256[$i]})); then
        passesBoth[$i]=${passes256[$i]}     
    fi
done

错误:

./partii.sh: line 46: 102==: syntax error: operand expected (error token is "=")
./partii.sh: line 46: ==103: syntax error: operand expected (error token is "==103")

程序仍然运行并给出了我想要的结果,但是我在运行时遇到了这两个错误。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

您正在尝试使用bash的算术上下文测试两个数字是否相等。让我们简化并观察错误消息:

$ ((2==)) && echo yes
bash: ((: 2==: syntax error: operand expected (error token is "==")
$ ((==2)) && echo yes
bash: ((: ==2: syntax error: operand expected (error token is "==2")

上述匹配与您观察到的错误消息非常接近。

以下,当然按预期工作:

$ ((2==2)) && echo yes
yes

根据您观察到的消息,似乎${passes212[$i]}${passes256[$i]}的值为空

让我们再试一次,但是使用带或不带指定值的变量:

$ x=2; y=""; (($x==$y)) && echo yes
bash: ((: 2==: syntax error: operand expected (error token is "==")
$ x=""; y=2; (($x==$y)) && echo yes
bash: ((: ==2: syntax error: operand expected (error token is "==2")

如果变量的值为空,那么当根本没有变量时,我们会得到与上面相同的错误消息。这似乎证实了我们的诊断。

解决方案是确保两个数组都已分配值。