IF statement for float numbers in bash

Issue

I’m relatively new in bash coding. I wrote a little script, that is a lopp through a txt file.

while read element1 element2 element3; do
if [ $element3 -lt 0.049 ]
then
operation
else
operation
fi
done < /path/file.txt

I am aware that the code above doesn’t work for floats.

I would like to use one of the element of the txt file in an if statement, but this specific element is a decimal number.

I have also seen an example using awk, but I didn’t understand it because using awk requires to change the code in non-familiar way to me.

So, is there a simple line of code to compare decimal numbers in if statements?

Solution

Here a simple solution using bc tool:

INPUT_VALUE=1.0
REF_VALUE=0.05

echo "${INPUT_VALUE} >= ${REF_VALUE}" | bc | grep -q 1

if [ $? == 0 ]; then
    echo "Greater or equal."
else
    echo "Lower."
fi

Answered By – Antonio Petricca

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published