与在bash变量浮点比较 [英] Floating point comparison with variable in bash

查看:62
本文介绍了与在bash变量浮点比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲浮点变量比较为整数。
我知道这是不是最好的做bash的,但我的整个脚本已经写在bash。
$数目可以是任意整数。如果低于或等于50,我想输出1,对于所有其他我想与其他变量k的输出。这是我到目前为止有:

 数= 43
测试= $(回声规模= 2; $号/ 50| BC -l)
回声$测试
对于k {中} 1..5

    如果[$测试-le 1]
    然后回声输出    ELIF [$测试-gt $ K]
    然后回声输出$ K
    科幻
DONE

如果我试图用试验= 0.43,第一循环甚至不工作。我认为这是一个整数和浮点做对比,但不能使它工作。

什么我失踪?

PS:此 [0.43:命令未找到是端子输出


解决方案

猛砸不能处理花车。管 BC 而不是:

 如果[$(回声$试验> $ K| BC)当量1]

您看到虽然该错误是因为测试命令(即 [)之前和之后<需要空间/ p>

有更好的使用((...)),因为你比较的数字是这样的:

  IF(($(BC&LT;&LT;&LT;$试验&gt; $ K)))

在循环中的一部分,应该是这样的:

  IF(($(BC&LT;&LT;&LT;$测试&LT; = 1)))
然后
    回声输出
ELIF(($(BC&LT;&LT;&LT;$试验&gt; $ K)))
然后
    回声输出$ K
科幻

关系前pressions评估为0,如果关系是假的,1,如果关系是真正的[的来源。不过要注意的是 GNU的BC A的行为,并且它不是 POSIX compiant。

I want to compare a floating point variable to an integer. I know this is not the best to do with bash, but my whole script is already written in bash. $number can be any integer. If it below or equal 50, I want output1, for all others I want an output with the other variable k. This is what I have so far:

number=43
test=$(echo "scale=2; $number/50" | bc -l)
echo "$test"
for k in {1..5}
do
    if ["$test" -le 1]
    then echo "output"

    elif ["$test" -gt $k]
    then echo "output$k"
    fi
done

If I try with test=0.43, the first loop does not even work. I think it has to do with an integer and a floating point comparison but cannot make it work.

Anything I am missing?

PS:this [0.43: command not found is what the terminal outputs.

解决方案

Bash can't handle floats. Pipe to bc instead:

if [ $(echo " $test > $k" | bc) -eq 1 ]

The error you see though is because the test command (i.e. the [) needs spaces before and after

It is even better to use (( ... )) since you compare numbers like this:

if (( $(bc <<< "$test > $k") ))

The part in the loop should look like this:

if (( $(bc <<< "$test <= 1") ))
then
    echo "output"
elif (( $(bc <<< "$test > $k") ))
then
    echo "output$k"
fi

Relational expressions evaluate to 0, if the relation is false, and 1 if the relation is true [source]. Note however that is a behavior of GNU bc, and it is not POSIX compiant.

这篇关于与在bash变量浮点比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆