Bash, lesson 3
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.
The operators are the same as in C:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+, -, * |
2 exercises to try what you just read.
| 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.
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.
Bash arithmetic has no decimals. $((7 / 2)) is 3, and $((2.5 + 1)) is a syntax error.
Two tricks cover most needs:
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.$(( (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.
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)).
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
35Each pays: D.CC
Leftover cents: N10000
3Each pays: 33.33
Leftover cents: 1