Bash arithmetic is integer arithmetic. It is useful for counters, totals, and small control decisions.

Program

Play the script to watch count change, then feed a second calculation.

count
arithmetic.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

count=7
count=$((count + 5))
half=$((count / 2))
echo "$count:$half"
#!/usr/bin/env bash

count=3
count=$((count + 5))
half=$((count / 2))
echo "$count:$half"
#!/usr/bin/env bash

count=11
count=$((count + 5))
half=$((count / 2))
echo "$count:$half"
  1. count ← 7

    3count=74count=$((count + 5))
    values this step7count
  2. count ← 12

    3count=74count=$((count + 5))5half=$((count / 2))
    values this step7 12count
  3. half ← 6

    4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"
    values this step6half12count
  4. echo "$count:$half"

    5half=$((count / 2))6echo "$count:$half"
    output12:6
    values this step12count6half
  1. count ← 3

    3count=34count=$((count + 5))
    values this step3count
  2. count ← 8

    3count=34count=$((count + 5))5half=$((count / 2))
    values this step3 8count
  3. half ← 4

    4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"
    values this step4half8count
  4. echo "$count:$half"

    5half=$((count / 2))6echo "$count:$half"
    output8:4
    values this step8count4half
  1. count ← 11

    3count=114count=$((count + 5))
    values this step11count
  2. count ← 16

    3count=114count=$((count + 5))5half=$((count / 2))
    values this step11 16count
  3. half ← 8

    4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"
    values this step8half16count
  4. echo "$count:$half"

    5half=$((count / 2))6echo "$count:$half"
    output16:8
    values this step16count8half

Follow the Counter

  1. count starts at 7.
  2. The arithmetic update adds 5, so count becomes 12.
  3. half=$((count / 2)) uses integer division.
  4. 12 / 2 gives 6.
  5. The script prints 12:6. | starting count | after + 5 | half | output | | --- | --- | --- | --- | | 3 | 8 | 4 | 8:4 | | 7 | 12 | 6 | 12:6 | | 11 | 16 | 8 | 16:8 |
integer arithmetic Bash arithmetic drops fractional parts because it works with integers.
counter update A variable can be read and assigned again in the same arithmetic expression.

Exercise: arithmetic.sh

Reproduce the default output 12:6, then try the listed count values 3 and 11 and predict each output before running it.