考虑下面的代码片段:
#!/bin/bash
#This program tests the if statement in bash.
for num in {0..99}
do
if [ ${num} -ge 50 ] && [ ${num} -le 59 ] || [ ${num} -ge 30 ] && [ ${num} -le 39 ]; then
echo "The number ${num} satisfies the condition."
else
echo "The number ${num} does not satisfy the condition."
fi
done
上述语句的输出为:
The number 30 satisfies the condition.
The number 31 satisfies the condition.
The number 32 satisfies the condition.
The number 33 satisfies the condition.
The number 34 satisfies the condition.
The number 35 satisfies the condition.
The number 36 satisfies the condition.
The number 37 satisfies the condition.
The number 38 satisfies the condition.
The number 39 satisfies the condition.
The number 50 does not satisfy the condition.
The number 51 does not satisfy the condition.
The number 52 does not satisfy the condition.
The number 53 does not satisfy the condition.
The number 54 does not satisfy the condition.
The number 55 does not satisfy the condition.
The number 56 does not satisfy the condition.
The number 57 does not satisfy the condition.
The number 58 does not satisfy the condition.
The number 59 does not satisfy the condition.
其余的输出语句确认要检查的条件。它们不是为了简洁而粘贴在这里的。我的问题是:
在我看来,数字30-39和50-59都满足if语句条件,但是输出完全是违反直觉的。将if语句条件更改为:
if [ ${num} -ge 30 ] && [ ${num} -le 39 ] || [ ${num} -ge 50 ] && [ ${num} -le 59 ]; then
输出显示为正常输出,其中30-39和50-59范围都满足条件。为什么在上面的语句中条件的顺序如此重要?
注意:我不确定这是否相关,但我使用的是bash version4.0.23(1)-release (i386-redhat-linux-gnu)
发布于 2011-04-04 11:29:08
像这样的问题通常是运算符的优先级问题。你写的是基本的((A && B ) || C) && D(从左到右求值),但是你想要(A &B) || (C && D)。
如果你用括号括起你的and条件,它就会像预期的那样工作:
if ([ ${num} -ge 50 ] && [ ${num} -le 59 ]) || ([ ${num} -ge 30 ] && [ ${num} -le 39 ]); then
https://stackoverflow.com/questions/5537710
复制