Floating point comparison in shell

前端 未结 7 1419
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 17:38

Can you please suggest to me the syntax for doing floating point comparison in a Bash script? I would ideally like to use it as part of an if statement. Here is

7条回答
  •  猫巷女王i
    2020-11-27 18:10

    bc is your friend:

    key1="12.3"
    result="12.2"
    if [ $(bc <<< "$result <= $key1") -eq 1 ]
        then
        # some code here
    fi
    

    Note the somewhat obscure here string (<<<) notation, as a nice alternative to echo "$result <= $key1" | bc.

    Also, the un-bash-like bc prints 1 for true and 0 for false.

提交回复
热议问题