How to compare two floating point numbers in Bash?

前端 未结 17 2158
無奈伤痛
無奈伤痛 2020-11-22 02:17

I am trying hard to compare two floating point numbers within a bash script. I have to variables, e.g.

let num1=3.17648e-22
let num2=1.5

No

17条回答
  •  醉酒成梦
    2020-11-22 02:36

    awk and tools like it (I'm staring at you sed...) should be relegated to the dustbin of old projects, with code that everyone is too afraid to touch since it was written in a read-never language.

    Or you're the relatively rare project that needs to prioritize CPU usage optimization over code maintenance optimization... in which case, carry on.

    If not, though, why not instead just use something readable and explicit, such as python? Your fellow coders and future self will thank you. You can use python inline with bash just like all the others.

    num1=3.17648E-22
    num2=1.5
    if python -c "exit(0 if $num1 < $num2 else 1)"; then
        echo "yes, $num1 < $num2"
    else
        echo "no, $num1 >= $num2"
    fi
    

提交回复
热议问题