if语句的不同行为的原因 - bash

时间:2011-04-04 11:18:17

标签: bash scripting if-statement conditional-statements

请考虑以下代码段:

#!/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版本4.0.23(1)-release(i386-redhat-linux-gnu)

1 个答案:

答案 0 :(得分:4)

这样的问题通常是运营商的优先问题。 你写的基本上是((A&& B)|| C)&& D(从左到右评估),但你想要(A&& B)|| (C& D)。

如果你围绕条件设置括号,它就会像预期的那样工作:

if ([ ${num} -ge 50 ] && [ ${num} -le 59 ]) || ([ ${num} -ge 30 ] && [ ${num} -le 39 ]); then