You will definitely need to do some math sometime or the other on the shell. As always ‘expr’ was the most popular thing out there to do complicated mathematical expressions. I was looking at some other options as well when I came across the bc and dc tools. I will explain each one of them in this post.
expr
This is by far the most famous for doing some math on the bash shell. There are two kinds mainly. One on string expressions and then the usual numericals. I would be writing about the later.
expr 40 % 5 0 expr 40 / 5 8 expr 40 / 5 / 8 1 expr 40 / 5 / 8 + 1 2 expr 40 / 5 / 8 + 1 * 10 expr: syntax error
Of course, while doing multiplication you need to use the escaped character ‘\’ backslash. And thus,
expr 40 / 5 / 8 + 1 \* 10 11
The brackets, division, multiplication, addition and subtraction rules also govern here. Now lets look at the others.
bc
This is a language bc that supports arbitrary precision numbers with interactive execution of statements. It starts by processing code from all the files listed on the command line in the order listed. Now a neat way to calculate stuff is:
echo 2*30/3 | bc 20 echo "20 + 5 * 3" | bc 35
Again this follows the basic BODMAS rules.
dc
Stands for desk calculator. Its an interactive calculator on the shell. It supports the basic arithmetic and uses the standard + – / * symbols but entered after the digits. Once you enter the symbol, get the calculated output by passing ‘p’ similar to our ‘=’ symbol on the calculator. And you can keep going.
dc 98 9 * p 882 10 / p 88
If I find more useful tools, I’ll update this post. If you have better ideas to implement this, feel free to suggest!