bash脚本中的浮点数比较

时间:2016-03-01 22:14:10

标签: bash shell

我尝试将浮点数与-gt进行比较,但它表示该点期望整数值。这意味着它无法处理浮点数。然后我尝试了以下代码

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

但输出错误。这是输出 -

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

此处no已回显,但应为yes。我认为这是因为它显示的错误。有谁能够帮我。

2 个答案:

答案 0 :(得分:2)

如果您想使用bc,请按照以下方式使用它:

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

答案 1 :(得分: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
相关问题