Kiran Kiran - 3 months ago 24
Linux Question

Floating Point Comparison in Shell Script

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 a small code snippet :

key1="12.3"
result="12.2"

if (( $result <= $key1 ))
then
# some code here
fi

Answer

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