More Bash answers

by Danny
Published 2 min read

Bash does whole-number maths with $(( )) and (( )), but it has no decimals. Learn the integer syntax, its traps, and how to use bc or awk when you need fractions.

The short answer

#

Use arithmetic expansion, $(( )), to calculate a value and (( )) to update a variable or test a condition. Both work with whole numbers only. For decimals, hand the sum to bc or awk.


_10
a=7
_10
b=2
_10
_10
echo $(( a + b )) # 9
_10
echo $(( a / b )) # 3, not 3.5
_10
(( a++ )) # a is now 8
_10
_10
echo "scale=2; 7 / 2" | bc # 3.50

Why it happens

#

Bash stores every variable as a string. When you write a+b outside an arithmetic context, Bash just joins the text, so echo a+b prints a+b and echo $a+$b prints 7+2. Arithmetic only happens inside $(( )), (( )), let or a variable declared with declare -i.

Inside those contexts Bash uses fixed-width signed integers (64-bit on modern systems). There is no floating point type at all, so division truncates towards zero and a value such as 1.5 is a syntax error. That is a design decision of the shell, not a bug, which is why decimals always need an outside tool.

How to fix it

#

Use $(( )) for integer maths

$(( )) expands to the result, so you can assign it, print it or pass it to a command. Inside the brackets you can leave off the $ on variable names, and spaces are allowed.


_10
count=5
_10
total=$(( count * 3 + 1 )) # 16
_10
remainder=$(( 17 % 5 )) # 2
_10
power=$(( 2 ** 10 )) # 1024
_10
half=$(( total / 2 )) # 8
_10
_10
echo "Total is $total"

The usual operators are all there: + - * / %, ** for powers, comparison operators, && and ||, bit operators and the ternary cond ? a : b.

Use (( )) to change a variable or test a value

(( )) runs the calculation for its side effect and sets the exit status, so it fits naturally in if and loops.


_10
retries=0
_10
_10
while (( retries < 3 )); do
_10
echo "Attempt $(( retries + 1 ))"
_10
(( retries += 1 ))
_10
done
_10
_10
if (( retries >= 3 )); then
_10
echo "Giving up"
_10
fi

Use bc for decimals

bc is a calculator that reads expressions from standard input. Set scale to choose how many digits appear after the decimal point, or pass -l to load the maths library, which sets the scale to 20 and adds functions such as s() for sine and l() for natural log.


_10
price=19.99
_10
qty=3
_10
_10
total=$(echo "scale=2; $price * $qty" | bc)
_10
echo "$total" # 59.97
_10
_10
echo "10 / 3" | bc -l # 3.33333333333333333333

bc does not round when it trims to scale; it truncates. If you need rounding, format the result with printf.


_10
printf '%.2f\n' "$(echo '10 / 3' | bc -l)" # 3.33

Use awk when bc is not installed

Some minimal containers do not ship bc, but awk is almost always present and uses floating point.


_10
awk -v a=7 -v b=2 'BEGIN { printf "%.2f\n", a / b }' # 3.50

Passing values with -v is safer than pasting them into the program text.

Common pitfalls

#
  • Leading zeros mean octal. $(( 08 + 1 )) fails with "value too great for base" because Bash reads 08 as octal. This bites when you parse dates or times. Force base 10 with $(( 10#$month + 1 )).
  • (( )) can trip set -e****. When the result of (( )) is 0, its exit status is 1. So (( count++ )) with count=0 returns failure and stops a script running under set -e. Use (( count += 1 )) or count=$(( count + 1 )) instead.
  • Integer division surprises. $(( 5 / 2 )) is 2. Multiply first if you want a percentage: $(( part * 100 / whole )).
  • Division by zero is an error, not infinity. Check the divisor before you divide.
  • expr and let are older forms. They still work but $(( )) is clearer and does not need escaping for *.
  • Comparing decimals with -lt fails because [ ] tests only accept integers. Compare in bc (echo "1.5 < 2" | bc prints 1 for true) or in awk.
#

Was this resource helpful?