Expansion and Data
Arithmetic
Updating Counters
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.
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"
count ← 7
3count=74count=$((count + 5))values this step7countcount ← 12
3count=74count=$((count + 5))5half=$((count / 2))values this step7 → 12counthalf ← 6
4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"values this step6half12countecho "$count:$half"
5half=$((count / 2))6echo "$count:$half"output12:6values this step12count6half
count ← 3
3count=34count=$((count + 5))values this step3countcount ← 8
3count=34count=$((count + 5))5half=$((count / 2))values this step3 → 8counthalf ← 4
4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"values this step4half8countecho "$count:$half"
5half=$((count / 2))6echo "$count:$half"output8:4values this step8count4half
count ← 11
3count=114count=$((count + 5))values this step11countcount ← 16
3count=114count=$((count + 5))5half=$((count / 2))values this step11 → 16counthalf ← 8
4count=$((count + 5))5half=$((count / 2))6echo "$count:$half"values this step8half16countecho "$count:$half"
5half=$((count / 2))6echo "$count:$half"output16:8values this step16count8half
Follow the Counter
countstarts at7.- The arithmetic update adds
5, socountbecomes12. half=$((count / 2))uses integer division.12 / 2gives6.- 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.