Bourne Shell条件运算符

时间:2017-05-09 13:09:20

标签: conditional sh

我在玩Bourne Shell时玩得很开心,但我面临着一个非常神秘的情况:

#! /bin/sh

a=1
b=2
c="0 kB/s"

if [ "$a" -eq 1 ] ; then echo "a = 1: true" ; else echo "a =  1: false" ; fi
if [ "$b" -gt 0 ] ; then echo "b > 0: true" ; else echo "b > 0: false" ; fi
if [ "$c" != "0 kB/s" ] ; then echo "c <> 0: true" ; else echo "c <> 0: false" ; fi
if [ "$a" -eq 1 ] || [ "$b" -gt 0 ] ; then echo "a = 1 or b > 0: true" ; else echo "a = 1 or b > 0: false" ; fi
if [ "$a" -eq 1 ] || [ "$b" -gt 0 ] && [ "$c" != "0 kB/s" ] ; then echo "a = 1 or b > 0 and c <> 0: true" ; else echo "a = 1 or b > 0 and c <> 0: false" ; fi
if [ true ] || [ true ] && [ false ] ; then echo "true or true and false: true" ; else echo "true or true and false: false" ; fi

给我以下结果:

a = 1: true
b > 0: true
c <> 0: false
a = 1 or b > 0: true
a = 1 or b > 0 and c <> 0: false
true or true and false: true

简短的问题:为什么我得不到a = 1 or b > 0 and c <> 0: true

非常感谢你的帮助......

1 个答案:

答案 0 :(得分:0)

||&&具有相同的优先级,与逻辑AND运算符比逻辑OR绑定得更紧密的语言不同。这意味着您编写的代码等同于

if { [ "$a" -eq 1 ] || [ "$b" -gt 0 ]; } && [ "$c" != "0 kB/s" ] ; then
  echo "a = 1 or b > 0 and c <> 0: true"
else
  echo "a = 1 or b > 0 and c <> 0: false"
fi

而不是预期的

if [ "$a" -eq 1 ] || { [ "$b" -gt 0 ] && [ "$c" != "0 kB/s" ]; } ; then
  echo "a = 1 or b > 0 and c <> 0: true"
else
  echo "a = 1 or b > 0 and c <> 0: false"
fi