Performing Math Calculation in Bash
I use math in bash scripts a lot, from simple crontab reports to Nagios monitoring plugins… Here is few small examples on how to do some maths in Bash with integers or float.
Integer Math
First way to do math with integer (and only integer) is to use the command “expr — evaluate expression”.
1 2 3 4 5 6 7 8 9 10 11 

When doing a “multiply by” make sure to backslash the “asterisk” as it’s a wildcard in Bash used for expansion.
Another alternative to expr, is to use the bash builtin command let.
1 2 3 4 5 6 7 8 9 10 11 

Also, you can simply use the parentheses or square brackets :
1 2 3 4 5 6 7 

This allow you to use Cstyle programming :
1 2 3 4 5 6 7 8 9 10 

Floating point arithmetic
You can’t do floating point arithmetic natively in bash, you will have to use a command line tool, the most common one being “bc  An arbitrary precision calculator language”.
1 2 3 4 5 6 7 8 9 

Of course you can use the STDIN to send your formula to “bc” then get the output on STDOUT.
1 2 

or by using the heredoc notation:
1 2 

I encourage you too take a look at the man pages to get more detail on how it works (man bc).
There are four special variables, scale, ibase, obase, and last. scale defines how some operations use digits after the decimal point. The default value of scale is 0. ibase and obase define the conver
sion base for input and output numbers. The default for both input and output is base 10. last (an extension) is a variable that has the value of the last printed number.
The “scale” variable is really important for the precision of your results, especially when using integers only (Note: you can also use “bc l” to use mathlib and see the result at max scale) .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 

Another way to do floating point arithmetic is to use AWK:
1 2 

You can use printf to adjust the precision of the results:
1 2 

When using negative values, make sure to leave a white space between signs.
1 2 3 

1 2 

If you want to go further, you can check my post Advanced Math Calculation in Bash using GNU bc.