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

Multiplication in bash

$ let x=5*2
$ echo $x

Addition in bash, increment variable by one

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

Subtraction in bash / decrement variable by one

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

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 containing the awk part in a re-usable function named float and also usage example in the end.

# this function helps to compare floating point numbers  
float() {  
    if [ $# -ne 2 ]; then  
        echo "incorrect number of arguments"  
        exit 1  
        # 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"; }'  
if [ "`float ${1} ${2}`" = "less" ];then 
   echo "${1} is less than ${2}" 
elif [ "`float ${1} ${2}`" = "more" ];then 
   echo "${1} is greater than ${2}" 
   echo "${1} is equal to ${2}" 

Invoking the script:

$ chmod 700  
$ ./ 3 5 
3 is less than 5 
$ ./ 5 3.5 
5 is greater than 3.5 
$ ./ 2.5678734 2.56787 
2.5678734 is greater than 2.56787 
$ ./ 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.