Sometime, we need to compare floating values in bash. But like we can compare integers in bash, will not work for floating numbers. In integer comparison, we used “lt/le/eq/gt/ge”, which makes possible to compare integer values in bash script.
Let’s see with examples what exactly happen in case we treat floating values and integer with same comparison operator.


#!/bin/bash
read -p “Type a floating number :” number
if [ $number -lt 50 ]; then
echo “Number tha you mentioned in smaller than 50”
else
echo “Number tha you mentioned in greater than 50”
fi
=====================================
        OutPut with Float
#./as
Type a floating number :34.78
./as: line 3: [: 34.78: integer expression expected
Number tha you mentioned in greater than 50
        OutPut with integer
#./as
Type a floating number :23
Number tha you mentioned in smaller than 50

With this small bash script we can easily able to understand, why we shouldn’t compare floating numbers as we do integer.Let’s see one way I used to compare floating numbers.


#!/bin/bash
read -p “Type a floating number :” number
if [ $(echo “$number>50″| bc) -eq 0 ]; then
echo “Number tha you mentioned in smaller than 50”
else
echo “Number tha you mentioned in greater than 50”
fi
=====================================
        OutPut with Float
#./as
Type a floating number :34.89
Number that you mentioned in smaller than 50
#./as
Type a floating number :56.09
Number tha you mentioned in greater than 50
        OutPut with integer
#./as
Type a floating number :23
Number tha you mentioned in smaller than 50
#./as
Type a floating number :67
Number tha you mentioned in greater than 50