【发布时间】: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