如何在 Bash 中进行浮动比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11541568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:26:52  来源:igfitidea点击:

How to do float comparison in Bash?

bashshellfloating-pointcomparison

提问by igustin

lock_percent=$(echo "scale = 5; $value2*100/$value1" | bc)
value=`echo "$lock_percent" | bc`

    if [[ "$value" > "" ]]; then
       echo "Lock Percentage:$value percentage State Critical"
       exit $STATE_CRITICAL
    fi

I am not able to perform a float comparison with this. I am not able to understand where I am going wrong.

我无法对此进行浮点比较。我无法理解我哪里出错了。

回答by igustin

Bash itself can't use float. In this case maybe you can multiply by 10 or 100 (etc.) and get integer value which you can compare. Or, you can use bccomparison and return value:

Bash 本身不能使用浮动。在这种情况下,也许您可​​以乘以 10 或 100(等)并获得可以比较的整数值。或者,您可以使用bc比较和返回值:

echo "10.2>10.1" | bc

回答by slitvinov

# float number comparison
fcomp() {
    awk -v n1="" -v n2="" 'BEGIN {if (n1+0<n2+0) exit 0; exit 1}'
}

# test and example
fcomp_test() {
    if fcomp "" ""; then
       echo "<"
    else
       echo ">="
    fi
}

fcomp_test 0.0 0.1
fcomp_test 0.1 0.1
fcomp_test -0.1 0.1
fcomp_test 1e3 1e4
fcomp_test -1.34e3 1.03e4
fcomp_test ' 0 ' ' 1 '