Learn/Bash/3. Arithmetic
Lesson 3 of 8
Sign in

Bash, lesson 3

Arithmetic

Bash variables hold text, but inside an arithmetic expansion Bash treats them as integers. Write the calculation between $(( and )), and Bash replaces the whole thing with the result:

Inside $(( )) you do not need $ in front of variable names (it still works if you write it), spaces are allowed anywhere, and an unset or empty variable counts as 0.

Operators

The operators are the same as in C:

OperatorMeaningExampleResult
+, -, *

2 exercises to try what you just read.

Exercise 1

Add two numbers

Press Ctrl Enter or Check to test your code.

Exercise 2

Split the bill

Press Ctrl Enter or Check to test your code.

add, subtract, multiply
$((7 * 3))
21
/whole-number division, drops the remainder$((17 / 5))3
%remainder$((17 % 5))2
**power$((2 ** 10))1024

** is done first, then *, / and %, then + and -. Parentheses change the order as usual: $(( (a + b) * 2 )).

Division by zero stops the command with an error message, so check your divisor when it comes from input.

Changing variables: (( ))

Without the leading $, the double parentheses run a calculation for its effect, such as updating a variable. This is where the C-style shortcuts shine:

You can also write count=$((count + 1)). Both styles are common.

Whole numbers only

Bash arithmetic has no decimals. $((7 / 2)) is 3, and $((2.5 + 1)) is a syntax error. Two tricks cover most needs:

  • Work in smaller units. Store money in cents and time in seconds, then convert for display: printf "%d.%02d\n" $((cents / 100)) $((cents % 100)) prints 12.05 for 1205 cents. %02d pads a number to two digits with a leading zero.
  • Round instead of truncating by adding half the divisor first: $(( (total + count / 2) / count )) rounds the average to the nearest whole number for positive values.

For real floating-point maths, scripts usually call an external tool such as bc or awk, but for counting, totals and percentages, integers are enough.

Watch out for leading zeros

A number written with a leading 0 is read as octal (base 8), so $((08 + 1)) is an error and $((010)) is 8. If input might have leading zeros, such as 09 from a time, force base 10 with 10#: $((10#$hour + 1)).

Further reading

  • Bash manual: Shell arithmetic
  • Bash manual: Arithmetic expansion

Read two whole numbers, one per line, and print their sum.

Sample input:

Sample output:

Read a bill total in cents on the first line and the number of people on the second. Each person pays the total divided by the number of people, rounded down to a whole cent; the person who paid the bill covers the cents left over. Print:

where D.CC is the share in euros and cents, with the cents always two digits.

Sample input:

Sample output:

read -r a
read -r b
echo "Sum: $((a + b))"
count=0
((count++))       # count is now 1
((count += 10))   # count is now 11
((total = count * 2))
2
3
5
Each pays: D.CC
Leftover cents: N
10000
3
Each pays: 33.33
Leftover cents: 1