Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two decimal numbers in bash/awk?

Tags:

bash

shell

awk

People also ask

How do I compare decimals in bash?

For integer comparison, it's [[ 3 -lt 2 ]] or (( 3 < 2 )) . If you want floating point comparison, you need ksh93 , zsh or yash or an external utility like awk or perl ; bash can't do it. Or even for that matters: if compare '"bar" < "foo"'...

Can bash handle decimals?

Bash itself cannot support floating point numbers, but there is a program called bc that can do decimal arithmetic. You script should be rewrite to use BC (aka Best Calculator) or another other utility.

How do I compare two integer variables in bash?

You can take the same or different values as per your choice. Then we have initialized the “if” statement to contrast the two variables by an operator “-eq”. This will check whether the two variables are equal or not. If the two variables are equal, it will show the message displayed within the first echo phrase.


You can do it using Bash's numeric context:

if (( $(echo "$result1 > $result2" | bc -l) )); then

bc will output 0 or 1 and the (( )) will interpret them as false or true respectively.

The same thing using AWK:

if (( $(echo "$result1 $result2" | awk '{print ($1 > $2)}') )); then

if awk 'BEGIN{exit ARGV[1]>ARGV[2]}' "$z" "$y"
then
  echo z not greater than y
else
  echo z greater than y
fi

if [[ `echo "$result1 $result2" | awk '{print ($1 > $2)}'` == 1 ]]; then
  echo "$result1 is greater than $result2"
fi

Following up on Dennis's reply:

Although his reply is correct for decimal points, bash throws (standard_in) 1: syntax error with floating point arithmetic.

result1=12
result2=1.27554e-05


if (( $(echo "$result1 > $result2" | bc -l) )); then
    echo "r1 > r2"
else
    echo "r1 < r2"
fi

This returns incorrect output with a warning although with an exit code of 0.

(standard_in) 1: syntax error
r1 < r2

While there is no clear solution to this (discussion thread 1 and thread 2), I used following partial fix by rounding off floating point results using awk followed by use of bc command as in Dennis's reply and this thread

Round off to a desired decimal place: Following will get recursive directory space in TB with rounding off at the second decimal place.

result2=$(du -s "/home/foo/videos" | tail -n1 | awk '{$1=$1/(1024^3); printf "%.2f", $1;}')

You can then use bash arithmetic as above or using [[ ]] enclosure as in following thread.

if (( $(echo "$result1 > $result2" | bc -l) )); then
    echo "r1 > r2"
else
    echo "r1 < r2"
fi

or using -eq operator where bc output of 1 is true and 0 is false

if [[ $(bc <<< "$result1 < $result2") -eq 1 ]]; then
    echo "r1 < r2"
else
    echo "r1 > r2"
fi