Rodrigo Mendes da Rocha Rodrigo Mendes da Rocha - 5 months ago 14
Linux Question

Shell scripting - Comparing floating number within if then else

I need to make a comparison between floating numbers within the if.
For example,

if [1.1 -gt .45] && [1.1 -lt 2.9]

Then
...

fi

In the case of my program I've tried ...

if [ "$ {restogpsweek [0]} -gt 0.1"] && [ "$ {restogpsweek [0]} -lt 2.2"]

if [ "$ {restogpsweek [0]} -gt 0.1" | bc] && [ "$ {restogpsweek [0]} -lt 2.2" | bc]

if [

echo" $ {restogpsweek [0]} -gt 0.1 "| bc
] && [
echo" $ {restogpsweek [0]} -lt 2.2 "| bc
]

and "n" other things and not found ...

Does anyone know how to do these comparisons?

Hugs

Answer

bash can not do floating point arithmetics.

You can use a more advanced shell like zsh:

% [[ 1.1 -gt .45 ]] && echo 'Ok'
Ok

Or use bc to do the comparison:

$ echo '1.1 > .45' | bc -l
1

bc returns 1 if true and 0 if false.

Comments