Floating point comparison in shell

前端 未结 7 1362
伪装坚强ぢ
伪装坚强ぢ 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条回答
  • 2020-11-27 18:17

    bash doesn't do floats, use awk

    key1=12.3
    result=12.5
    var=$(awk 'BEGIN{ print "'$key1'"<"'$result'" }')    
    # or var=$(awk -v key=$key1 -v result=$result 'BEGIN{print result<key?1:0}')
    # or var=$(awk 'BEGIN{print "'$result'"<"'$key1'"?1:0}')
    # or 
    if [ "$var" -eq 1 ];then
      echo "do something"
    else
      echo "result more than key"
    fi
    

    there are other shells that can do floats, like zsh or ksh, you might like to try using them as well

    0 讨论(0)
提交回复
热议问题