Floating point comparison in shell

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.


another simple clear way with bc is this:

if ((`bc <<< "10.21>12.22"`)); then echo "true"; else echo "false"; fi

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 "BEGIN{ exit ($result <= $key1) }"
then
        # some code here that is only executed if $result <= $key1
fi

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


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

Tags:

Shell

Bash