Doing math in Bash

Bash supports simple integer (whole number) arithmetic operations with its arithmetic expressions. The syntax for expanding these is a set of double parentheses after the usual $ expansion sign:

$ num_a=3
$ num_b=2
$ printf 'The sum of the two numbers is: %u\n' "$((num_a + num_b))"
The sum of the two numbers is: 5

Notice in the preceding expression, "$((num_a + num_b))", we did not have to use the $ prefix to expand the num_a and num_b variables names. Assignments to other variables can be performed in the same way:

$ diff="$((num_a - num_b))"
$ printf 'The difference of the two numbers is: %u\n' "$diff"
The difference of the two numbers is: 1

We can do many different kinds of operations with these expressions, using both variables and literal numbers:

# Three raised to the power of two (squared)
$ printf '%u\n' "$((3**2))"
9
# 180 divided by 60
$ printf '%u\n' "$((180/60))"
3
# 1 or 0, depending on whether one number is greater than another
$ printf '%u\n' "$((2 > 1))"
1
$ printf '%u\n' "$((30 > 40))"
0

The full list of operations supported by these expressions is available after the "ARITHMETIC EVALUATION" in the Bash manual page. They are mostly taken from the C language, and the order in which the operations are evaluated is the same as in that language.