LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   bash: how to compare REAL numeric values? (http://www.linuxquestions.org/questions/linux-general-1/bash-how-to-compare-real-numeric-values-931601/)

muebi 02-27-2012 01:42 PM

bash: how to compare REAL numeric values?
 
Folks,

I would like to do an if conditional in bash to compare a numeric value, which is NOT an integer:

if [ "$VALUE" -eq 0.1 ]; then
... do something ...
else
... do something else ...
fi

If $VALUE is a real variable (e.g., 0.5) and not an integer and I get an error message saying: $VALUE: integer expression expected.

How can I do this?

AlucardZero 02-27-2012 01:49 PM

Bash does not handle floating point numbers. Use a real language (perl, python, C, etc) or a more modern shell (zsh) or insert calls to bc.

Dark_Helmet 02-27-2012 01:54 PM

Native bash: you can't

Two options:
1. move your script to another language with real number support (e.g. python or perl). If you are dealing with floating point numbers, the task (in my experience) is better suited to one of those other languages than a shell script.
2. invoke an external command that can support real valued conditionals

For #2, I usually rely on the bc command.

For instance:
Code:

user@localhost$ echo " 3.5 < 9.1" | bc -l
1
user@localhost$ echo " 3.5 > 9.1" | bc -l
0

Use the above with command substitution. For example:
Code:

variableName=$( echo "${operand1} < ${operand2}" | bc -l )
And then test the value of variableName.

EDIT:
Alucard beat me to it! ;)

H_TeXMeX_H 02-28-2012 08:00 AM

You can also do it in awk if bc is not available.

Quote:

Originally Posted by AlucardZero (Post 4613397)
Bash does not handle floating point numbers. Use a real language (perl, python, C, etc) or a more modern shell (zsh) or insert calls to bc.

So bash isn't a "real" language ?


All times are GMT -5. The time now is 03:52 PM.