Home > Mobile >  IF statement for float numbers in bash
IF statement for float numbers in bash

Time:07-07

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?

CodePudding user response:

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

CodePudding user response:

Using awk to compare and add greater or lower to each line

VALUE=0.049
while IFS=" " read -r comp element1 element2 element3; do
  if [ "$comp" = "lower" ];then
     operation
  else
     operation
  fi
done < <(awk -v val="$VALUE" '{print ($3 < val ? "lower": "greater"),$0}' /path/file.txt)
  • Related