简体   繁体   English

bash脚本中的浮点数比较

[英]floating point number comparison in bash script

I tried to compare floating point number by -gt but it says that point expecting integer value. 我试图通过-gt比较浮点数,但它表示该点期望整数值。 That means it can not handle floating point number . 这意味着它不能处理浮点数。 Then i tried the following code 然后我尝试了以下代码

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

But the output is wrong with error . 但是输出错误并带有错误。 Here is the out put- 这是输出-

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

Here the no is echoed but it should be yes . 在这里, no ,但应为yes I think that's because of the error it's showing. 我认为这是由于显示的错误。 can anybody help me. 有谁能够帮助我。

If you want to use bc use it like this: 如果要使用bc使用它:

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

Keep it simple, just use awk: 保持简单,只需使用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

or if you prefer avoiding ternary expressions for some reason (and also showing how to use a value stored in a shell variable): 或者如果您出于某种原因喜欢避免使用三元表达式(并且还显示了如何使用存储在shell变量中的值):

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

or: 要么:

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

or to bring it full circle: 或将其圈出一圈:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM