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? |
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.
|
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 Code:
variableName=$( echo "${operand1} < ${operand2}" | bc -l ) EDIT: Alucard beat me to it! ;) |
You can also do it in awk if bc is not available.
Quote:
|
All times are GMT -5. The time now is 03:11 PM. |