Simple integer calculations directly in bash

If you want to do some basic math with integers, you don’t need extra tools and can use double parentheses in bash.

[sim@GHOSTbook ~]$ echo $(( 4 + 5 * 6 ))
34

The order ist very important. You should always multiply prior to dividing.

For example if you want to print the percentage of 11/13:

[sim@GHOSTbook ~]$ echo $(( 11 / 13 * 100 ))
0
[sim@GHOSTbook ~]$ echo $(( 11 * 100 / 13 ))
84

Obviously 84 is far better than 0. If you want it even more precise, you can multiple by 10 for every decimal you want to know. Then you can split the result, print everything but the decimals, add a decimal point and the remaining decimals.

[sim@GHOSTbook ~]$ percentage=$(( 11 * 100 * 100 / 13 ))
[sim@GHOSTbook ~]$ echo ${percentage%??}.${percentage:(-2)}
84.61

1 thought on “Simple integer calculations directly in bash

Leave a Reply