Bash calculations

Bash builtin calculations support only INTEGERS!

The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands, the (( compound command, and Arithmetic Expansion).  Evaluation is done in fixed-width  integers  with  no  check  for  overflow, though division by 0 is trapped and flagged as an error.  The operators and their precedence, associativity, and values are the same as in the C language.

from $ man bash

Division in bash – lets divide 5 with 2 and see what result we get.

$ let x=5/2
$ echo $x
2

Multiplication in bash

$ let x=5*2
$ echo $x
10

Addition in bash, increment variable by one

$ let x=5+2
$ echo $x
7
$ let x++
8

Subtraction in bash / decrement variable by one

$ let x=5-2
$ echo $x
3
$ let x-- 
2

Comparing floating point numbers in bash

Bash sucks in floating point number comparison.

Try these out as an example:

$ x=2.5;y=3;if [ $x > $y ]; then echo "x is greater than y"; else echo "x is smaller than y";fi 
x is greater than y

$ x=5.5;y=3;if [ $x -gt $y ]; then echo "x is greater than y"; else echo "x is smaller than y";fi 
bash error - integer expected (evaluates false)          
x is smaller than y

To overcome the limitation use simple function and awk in your bash script.

Sample script test.sh containing the awk part in a re-usable function named float and also usage example in the end.

#!/bin/bash 
 
# this function helps to compare floating point numbers  
float() {  
    if [ $# -ne 2 ]; then  
  
        echo "incorrect number of arguments"  
        exit 1  
  
    else  
  
        # will give both floats to awk as variables and let the awk do the comparison  
        awk -v f1=${1} -v f2=${2} 'BEGIN{ if (f1<f2) print "less"; if (f1==f2) print "equal"; if (f1>f2) print "more"; }'  
  
    fi  
} 
 
 
if [ "`float ${1} ${2}`" = "less" ];then 
   echo "${1} is less than ${2}" 
elif [ "`float ${1} ${2}`" = "more" ];then 
   echo "${1} is greater than ${2}" 
else 
   echo "${1} is equal to ${2}" 
fi
 

Invoking the script:

$ chmod 700 test.sh  
$ ./test.sh 3 5 
3 is less than 5 
$ ./test.sh 5 3.5 
5 is greater than 3.5 
$ ./test.sh 2.5678734 2.56787 
2.5678734 is greater than 2.56787 
$ ./test.sh 2.5638734 2.56787  
2.5638734 is less than 2.56787

Works as a charm!

Check also how to calculate pi in bash.

If you found this useful, say thanks, click on some banners or donate, I can always use some beer money.