Bourne Shell 条件运算符
Bourne Shell Conditional Operators
我和 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
?
非常感谢您的帮助...
||
和 &&
具有相同的优先级,这与逻辑 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
我和 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
?
非常感谢您的帮助...
||
和 &&
具有相同的优先级,这与逻辑 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