Bash Math



Use Bash builtins (let, expr) for integer math and bc (a GNU numeric processing language) for floating point arithmetic in your bash scripts. Here are some examples.

Integer Math in Bash

The expr builtin can be used as a simple integer calculator. Results are rounded to the nearest integer and floating point is unknown. BE sure to escape the multiplication asterisks (*) to avoid Bash expansion.

bash$ expr 1 + 1
2
bash$ expr 3 \* 2
6
bash$ expr 6 / 3
2
bash$ expr 6 % 3
0
bash$ expr 3 / 2
1
bash$ expr 3 / 6
0
bash$ expr 6 \* 3.5
expr: non-numeric argument

Instead of expr(), you can also echo the output of $(( )) or $[ ].

bash$ expr 1 + 1
4
bash$ echo $((2 + 2))
4
bash$ echo $[2 + 2]
4

Use the bash builtin let for quick manipulation of bash variables.

bash$ NUM=41
bash$ let NUM+=1
bash$ echo $NUM
42

Floating Point Arithmetic in Bash

Using floating point in bash scripts requires an external calculator like GNU bc. Pipe your request to bc and note that escaping is not needed for quoted asterisks.

bash$ echo "3.8 + .4" | bc
4.2
bash$ echo '6 * 1.5' | bc
9.0

If all input values are integers, the bc option scale must be defined if you expect a floating point result.

bash$ echo '2 / 5' | bc
0
bash$ echo 'scale=2; 2 / 5' | bc
.40

You can also use the bash here string <<< to accomplish the same as a pipe of echo to bc:

bash$ echo 'scale=2; 2 / 5' | bc
.40
bash$ bc <<< 'scale=2; 2 / 5'
.40

Or, use bc -l to evoke the standard (but not default!) mathlib and see the result in floating point at max scale:

bash$ bc -l <<< '10.5 / 1'
10.50000000000000000000