How to compare two floating point numbers in Bash?

前端 未结 17 2169
無奈伤痛
無奈伤痛 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:53

    beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

    $ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
    NO
    
    $ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
    NO
    
    $ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
    YES
    

    I solved such problem with such shell/awk function:

    # get version of GNU tool
    toolversion() {
        local prog="$1" operator="$2" value="$3" version
    
        version=$($prog --version | awk '{print $NF; exit}')
    
        awk -vv1="$version" -vv2="$value" 'BEGIN {
            split(v1, a, /\./); split(v2, b, /\./);
            if (a[1] == b[1]) {
                exit (a[2] '$operator' b[2]) ? 0 : 1
            }
            else {
                exit (a[1] '$operator' b[1]) ? 0 : 1
            }
        }'
    }
    
    if toolversion grep '>=' 2.6; then
       # do something awesome
    fi
    

提交回复
热议问题