2014-01-20 98 views
1

我想比較3組然後我寫一個bash腳本,但結果是錯誤的。 請指導我的腳本Bash腳本多個字符串變量比較

#!/bin/bash 
function SCORETYPE { 
if [[ "$ENG1" < "$ENG2" || "$ENG3" < "$ENG4" || "$ENG5" > "$ENG6" ]]; then 
    STYPE="A" 
elif [[ "$ENG1" < "$ENG2" || "$ENG3" > "$ENG4" || "$ENG5" > "$ENG6" ]]; then 
    STYPE="B" 
elif [[ "$ENG1" > "$ENG2" || "$ENG3" < "$ENG4" || "$ENG5" < "$ENG6" ]]; then 
    STYPE="C" 
else 
    STYPE="D" 
fi 

echo "$STYPE" 
} 

# DATA for A 
ENG1=10; ENG2=15; ENG3=5; ENG4=7; ENG5=45; ENG6=15 
echo -n "Correct is A -- Answer is = "; SCORETYPE 

# DATA for B 
ENG1=3; ENG2=10; ENG3=8; ENG4=7; ENG5=40; ENG6=38 
echo -n "Correct is B -- Answer is = "; SCORETYPE 

# DATA for C 
ENG1=12; ENG2=9; ENG3=6; ENG4=9; ENG5=32; ENG6=50 
echo -n "Correct is C -- Answer is = "; SCORETYPE 

# DATA for D 
ENG1=12; ENG2=9; ENG3=9; ENG4=8; ENG5=32; ENG6=50 
echo -n "Correct is D -- Answer is = "; SCORETYPE 

結果

根@代理:/ tmp目錄#六multiple_var_test & & ./multiple_var_test

正確的是A - 答案是= A

正確是B - 答案是= A

正確答案是C - Answer is = A

正確的是d - 答案是= A

+2

您可能打算使用&&代替||。 ...如果其他條件對於或者||沒有意義運營商 –

回答

3

使用((而不是[[以評估算術表達式。

您還需要在您的條件下使用&&(和),而不是||(或)。

試試這個:

function SCORETYPE { 
if ((ENG1 < ENG2 && ENG3 < ENG4 && ENG5 > ENG6)); then 
    STYPE="A" 
elif ((ENG1 < ENG2 && ENG3 > ENG4 && ENG5 > ENG6)); then 
    STYPE="B" 
elif ((ENG1 > ENG2 && ENG3 < ENG4 && ENG5 < ENG6)); then 
    STYPE="C" 
else 
    STYPE="D" 
fi 

echo "$STYPE" 
} 

(注:在算術表達式,它是沒有必要前綴變量,一個$。)

+0

謝謝,我可以解決,因爲你的指導;-) – usr8655586

0

你有你的邏輯錯誤 - 應該和不OR,您需要用下面的代碼替換您的比較運算符:

function SCORETYPE { 
if [[ "$ENG1" -lt "$ENG2" && "$ENG3" -lt "$ENG4" && "$ENG5" -gt "$ENG6" ]]; then 
    STYPE="A" 
elif [[ "$ENG1" -lt "$ENG2" && "$ENG3" -gt "$ENG4" && "$ENG5" -gt "$ENG6" ]]; then 
    STYPE="B" 
elif [[ "$ENG1" -gt "$ENG2" && "$ENG3" -lt "$ENG4" && "$ENG5" -lt "$ENG6" ]]; then 
    STYPE="C" 
else 
    STYPE="D" 
fi 

echo "$STYPE" 
}