Bash Tutorial · Bash Scripting · Lesson 16 of 30

Bash Arithmetic

Integer maths with $(( )), counters, and floating-point calculations with bc or awk.

Create a free account to save this page, take notes and track your progress. Sign in

Integer arithmetic

$(( expression )) evaluates integer maths: + - * / % **, comparisons, and C-style ++/+=. Inside, you can use variable names without $.

$(( )) and (( ))
a=7; b=2
echo "sum=$((a + b)) div=$((a / b)) mod=$((a % b)) pow=$((a ** b))"
count=0
for i in 1 2 3; do (( count += i )); done
echo "count=$count"
(( count > 5 )) && echo "count is greater than 5"

Output

sum=9 div=3 mod=1 pow=49
count=6
count is greater than 5

Run this on your computer — see “Get Started” for setup.

Decimals

Bash only does integers (7 / 2 is 3). For decimals use awk or bc:

Decimals with awk
awk 'BEGIN { printf "%.2f\n", 7 / 2 }'
price=19.99; qty=3
awk -v p="$price" -v q="$qty" 'BEGIN { printf "total: %.2f\n", p * q }'

Output

3.50
total: 59.97

Run this on your computer — see “Get Started” for setup.

Test yourself

What is $((10 / 4)) in Bash?

  1. 2.5
  2. 2
  3. 3
  4. An error
Show answer

Answer: 2

Bash arithmetic is integer-only; the result is truncated.

Was this page helpful?