Category Archives: bash

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

Add sudo in front of the last issued command

If you ever forgot to put sudo in front of your command, you can use bash history manipulation to quickly correct your mistake.

Just use !!.

It will replace your last command right where you use it.

[sim@GHOSTbook ~]$ cat /etc/shadow
cat: /etc/shadow: Permission denied
[sim@GHOSTbook ~]$ sudo !!
sudo cat /etc/shadow
[sudo] password for sim: