2017-05-09 73 views
0

我有很多的樂趣與Bourne Shell中玩,但我現在面臨一個相當神祕的有關情況及條件: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

非常感謝您的幫助...

回答

0

||&&具有相同的優先級,在不同地方的語言邏輯與操作的優先級比邏輯或更緊密。這意味着你的代碼編寫相當於

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 
+0

謝謝,但那麼爲什麼我反正得'真或真假:TRUE'? –

+0

因爲'true'和'false'不是布爾常量;它們只是非空字符串,因此'[true]'和'[false]'都成功了(它們分別相當於'[-n true]'和'[-n false]')。 – chepner

+0

謝謝,在一個問題中兩個有用的答案! –