Arithmetic
Prerequisites: Variables
Bash does integer arithmetic inside $(( ... )).
a=17
b=5
echo $(( a + b ))
echo $(( a - b ))
echo $(( a * b ))
echo $(( a / b ))
echo $(( a % b ))
echo $(( a ** 2 ))
echo $(( (a + b) * 2 ))
22
12
85
3
2
289
44
- Inside
$(( )), variables don't need$. - Division is integer division —
17 / 5is3, with the remainder from%. **raises to a power.
Changing a variable
count=0
(( count++ ))
(( count += 10 ))
echo "$count"
11
(( ... )) on its own (without $) evaluates an expression — handy for
updating counters.
Decimals
Bash can't do decimal arithmetic. Use awk, which is available
everywhere:
awk 'BEGIN { printf "%.2f\n", 10 / 3 }'
price=19.99
awk -v p="$price" 'BEGIN { printf "%.2f\n", p * 1.2 }'
3.33
23.99
awk -v p="$price" passes a shell variable into awk. On many systems, the
bc calculator also works: echo "scale=2; 10 / 3" | bc.
Common mistakes
echo 7 / 2just prints the text7 / 2. Arithmetic needs$(( )).- Expecting
$(( 7 / 2 ))to be3.5. - Numbers with leading zeros are read as octal:
$(( 08 + 1 ))is an error. Strip leading zeros from dates like08, or write$(( 10#08 + 1 )).
Practice
Given minutes=135, print it as hours and minutes: 2h 15m.
Show solution
minutes=135
echo "$(( minutes / 60 ))h $(( minutes % 60 ))m"
2h 15m