2011-04-04 12 views
1

次のコードスニペットを考えてみましょう:理由 - bashの

#!/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の両方の範囲が条件を満たすように表示されます。なぜ上記の声明で条件の順序が重要なのですか?

注:(1)-release(I386-のredhat-linuxの-gnuの)このような

答えて

4

問題は、多くの場合の問題です私はこれが関連しているかどうかわからないが、私はbashのバージョン4.0.23を使用していますオペレータとの優先順位。あなたが書いた何 はbasicly((& & B)|| C)& & D(その左から右に評価)ですが、(& & B)欲しい|| (C & &D)。あなたは条件の周りにブラケットを作る場合

それは期待のように動作します:

if ([ ${num} -ge 50 ] && [ ${num} -le 59 ]) || ([ ${num} -ge 30 ] && [ ${num} -le 39 ]); then