Floating point comparison in shell

前端 未结 7 1361
伪装坚强ぢ
伪装坚强ぢ 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 17:57

    another simple clear way with bc is this:

    if ((`bc <<< "10.21>12.22"`)); then echo "true"; else echo "false"; fi
    
    0 讨论(0)
  • 2020-11-27 18:06

    I was using bc until now, I found in some distros there was not bc installed, and I did not want to go through sudo apt install bc but python was there. Using python:

      if python -c "import sys; sys.exit(0 if float($float_1) > float($float_2) else 1)"; 
        then
        echo "true"
             else
               echo "false"
      fi
    
    0 讨论(0)
  • 2020-11-27 18:07
    ### The funny thing about bash is this:
    > AA=10.3
    > BB=10.4
    ### It needs `$` for compare
    > [[ $AA > $BB ]] && echo Hello
    > [[ $AA < $BB ]] && echo Hello
    Hello
    

    Yeah, I know it's cheating but it works. And scientific notation does not work here.

    0 讨论(0)
  • 2020-11-27 18:09

    Using the exit() function of awk makes it almost readable.

    key1=12.3
    result=12.5
    
    # the ! awk is because the logic in boolean tests 
    # is the opposite of the one in shell exit code tests
    if ! awk "{ exit ($result <= $key1) }" < /dev/null
    then
            # some code here
    fi
    

    Note that there is not need to reuse the [ operator as if already uses the exit value.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 18:16

    yu can use this awk comparison inside a if clause, it will print 1 (true) if the condition is true else 0 (false), and those values will be interpreted as boolean vals by the if

    if (( $(awk 'BEGIN {print ("'$result'" <= "'$key1'")}') )); then
        echo "true"
    else
        echo "false"
    fi
    
    0 讨论(0)
提交回复
热议问题