首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >if语句- bash行为不同的原因

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

Stack Overflow用户
提问于 2011-04-04 19:18:17
回答 1查看 462关注 0票数 1

考虑下面的代码片段:

代码语言:javascript
代码运行次数:0
运行
复制
#!/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  

上述语句的输出为:

代码语言:javascript
代码运行次数:0
运行
复制
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语句条件更改为:

代码语言:javascript
代码运行次数:0
运行
复制
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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-04 19:29:08

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

如果你用括号括起你的and条件,它就会像预期的那样工作:

代码语言:javascript
代码运行次数:0
运行
复制
if ([ ${num} -ge 50 ] && [ ${num} -le 59 ]) || ([ ${num} -ge 30 ] && [ ${num} -le 39 ]); then
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5537710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档