2016-03-01 49 views
1

我試圖比較浮點數-gt,但它表示期望整數值的點。這意味着它無法處理浮點數。然後我試了下面的代碼在bash腳本中的浮點數比較

chi_square=4 
if [ "$chi_square>3.84" | bc ] 
then 
echo yes 
else 
echo no 
fi 

但輸出錯誤的錯誤。這裏是出put-

line 3: [: missing `]' 
File ] is unavailable. 
no 

這裏no是呼應,但它應該是yes。我認爲那是因爲它顯示的錯誤。有誰能夠幫助我。

+0

'bash'不能處理浮點,但Korn shell程序('ksh')即可。 – cdarke

回答

2

如果你想使用bc這樣使用它:

if [[ $(bc -l <<< "$chi_square>3.84") -eq 1 ]]; then 
    echo 'yes' 
else 
    echo 'no' 
fi 
0

保持簡單,只用awk:

$ awk -v chi_square=4 'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}' 
yes 

$ awk -v chi_square=3 'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}' 
no 

或者如果你喜歡避免三元表達式出於某種原因(也展示瞭如何使用存儲在一個shell變量的值):

$ chi_square=4 
$ awk -v chi_square="$chi_square" 'BEGIN{ 
    if (chi_square > 3.84) { 
     print "yes" 
    } 
    else { 
     print "no" 
    } 
}' 
yes 

或:

$ echo "$chi_square" | 
awk '{ 
    if ($0 > 3.84) { 
     print "yes" 
    } 
    else { 
     print "no" 
    } 
}' 
yes 

或把它完整的圓:

$ echo "$chi_square" | awk '{print ($0 > 3.84 ? "yes" : "no")}' 
yes