How to do float comparison in Bash?

自作多情 提交于 2019-12-22 01:34:16

问题


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

    if [[ "$value" > "$8" ]]; 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.


回答1:


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 bc comparison and return value:

echo "10.2>10.1" | bc



回答2:


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

# test and example
fcomp_test() {
    if fcomp "$1" "$2"; then
       echo "$1<$2"
    else
       echo "$1>=$2"
    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 '


来源:https://stackoverflow.com/questions/11541568/how-to-do-float-comparison-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!