【问题标题】:Reasons for different behaviour of if statement - bashif 语句不同行为的原因 - bash
【发布时间】:2011-07-29 02:32:09
【问题描述】:

考虑以下代码sn-p:

#!/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)

【问题讨论】:

    标签: bash scripting if-statement conditional-statements


    【解决方案1】:

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

    如果你在你的 and 条件周围加上括号,它会像预期的那样工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2013-06-16
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多