Search code examples
bashif-statement

How to compare float numbers in an if conditional in BASH?


My code is:

#!/bin/bash
rm N_Matrix.csv
Lineas=`wc -l $1| awk '{print $1}'`
for (( i = 1 ; i <= Lineas ; i++ ));
do
    Numer_1=`awk -vvar=$i 'NR==var' $1`
    for (( j = 1 ; j <= Lineas ; j++ ));
    do
        Numer_2=`awk -vvar=$j 'NR==var' $1`
        if (( ${Numer_1} -ge ${Numer_2} )); 
        then
            Descriptor=`echo "(($Numer_1)/($Numer_2))" | bc -l`
        else
            Descriptor=`echo "(($Numer_2)/($Numer_1))" | bc -l`
        fi
        echo $Descriptor >> $i.txt
    done
done

paste {1..29}.txt > N_Matrix.csv
rm *.txt

The content of my working file is:

10.1234567
20.1234567
30.1234567
40.1234567
15.1234567
25.1234567
35.1234567
45.1234567

I have an error on the if conditional and I have tried all possible combinations. But still I cannot see what the mistake is.

I get line 10: ((: 45.1234567 -ge 45.1234567 : syntax error: invalid arithmetic operator (error token is ".1234567 -ge 45.1234567 ")


Solution

  • The error is clearly indicated: there is invalid syntax line 10

            if (( ${Numer_1} -ge ${Numer_2} )); 
    

    I see three problems:

    • -ge is for operator [[ ... ]] and [ ... ] use (( ... >= ... )) instead
    • (( ... )) only support integer number. This is the main problem with your script
    • in (( ... )), variable should not use dollar (but it still works with it)

    It should work if you use bc to compare numbers

            result=$(bc -l <<< "${Numer_1} >= ${Numer_2}") # bc will print 1 if condition is true
            if [[ "${result}" == 1 ]] # check that bc printed 1