← Full reference

Arithmetic in bash

Integer math — $(( )), (( )), let, expr, number bases, and fractions via awk

Bash can only do integer math (64-bit, signed). The main tool is arithmetic expansion $((…)): it evaluates an expression and substitutes the result. The ((…)) construct evaluates without substituting and is suited for conditions and counters. let and the external expr utility are older ways you'll see in other people's scripts. For fractional numbers you need an external calculator: the sandbox image has no bc, but it does have awk and python3.

Syntax

x=$(( expression ))       # substitute the result
(( expression ))          # only evaluate; exit code 0 if the result is not 0
let 'expression' …        # same as (( )), expressions as separate arguments
expr a + b               # external command, each token is a separate argument

Inside $((…)) and ((…)) you can write variables without $: $((n * 2)). Spaces around operators are allowed.

Operators

OperatorWhat it doesExample → result
+ - * /addition, subtraction, multiplication, integer division$((7 / 2)) → 3
%remainder$((7 % 2)) → 1
**power$((2 ** 10)) → 1024
++ --increment / decrement (i++ and ++i)((i++))
= += -= *= /= %=assignment with an operation((sum += x))
< <= > >= == !=comparison: 1 — true, 0 — false$((5 > 3)) → 1
&& || !logical and, or, not$((1 && 0)) → 0
& | ^ ~ << >>bitwise operations and shifts$((1 << 4)) → 16
cond ? a : bternary operator$((x > 0 ? x : -x))
( )grouping$(( (2 + 3) * 4 )) → 20
,evaluate in order, the result is the last one$((a = 1, b = 2, a + b)) → 3

Number bases

NotationValue
0xff / 16#ffhexadecimal → 255
010 / 8#17octal (leading zero!) → 8 / 15
2#1010binary → 10
36#zany base from 2 to 64 → 35
10#08explicitly decimal — saves you from leading zeros

To go the other way, from decimal to another base, use printf: printf '%x\n' 255 → ff, printf '%o\n' 8 → 10.

Ways to compute

MethodExampleNotes
$((…))n=$((n + 1))the main one, POSIX; the result is a numeric string
((…))((n++)), if ((n > 10))bash only; exit code 0 if the result is not 0
letlet 'n = n * 2'like ((…)); quote an expression with spaces
declare -i nn='3 + 4' → 7the variable is always evaluated as an expression
exprexpr 3 \* 4external program; escape *, separate operands and operators with spaces
awkawk 'BEGIN { print 7 / 2 }' → 3.5fractional numbers and functions sqrt, int, exp, log, sin
python3 -cpython3 -c 'print(7 / 2)'fractions, big numbers, complex formulas

expr also works with strings: expr length hello → 5, expr substr hello 2 3 → ell.

Examples

# counter in a loop
count=0
for f in /etc/*.conf; do
    ((count++))
done
echo "configs: $count"

# condition on numbers
free_pct=12
if (( free_pct < 20 )); then
    echo "low on space"
fi

# division rounding up: (a + b - 1) / b
pages=$(( (95 + 10 - 1) / 10 ))     # 10

# integer percentages: multiply first, then divide
done=37; total=120
echo "$(( done * 100 / total ))%"   # 30%

# bytes to megabytes
size=5242880
echo "$(( size / 1024 / 1024 )) MiB"   # 5 MiB

# hexadecimal to decimal and back
echo $((16#1F))        # 31
printf '%X\n' 31       # 1F

# fractional division via awk, 2 decimal places
awk -v a=10 -v b=3 'BEGIN { printf "%.2f\n", a / b }'   # 3.33

# sum the numbers in a file column — also awk
printf '1.5\n2.25\n3\n' | awk '{ s += $1 } END { print s }'   # 6.75

# random number from 1 to 6
echo $(( RANDOM % 6 + 1 ))

# a number with a leading zero from date (08, 09) — set base 10 explicitly
month=$(date +%m)
echo $(( 10#$month + 1 ))

Pitfalls

  • Division is integer. $((7 / 2)) gives 3; the remainder is truncated toward zero: $((-7 / 2)) → -3. Use awk for fractions. Multiply before dividing: a * 100 / b, not a / b * 100.
  • Fractional numbers are a syntax error. $((3.5 + 1)) fails with invalid arithmetic operator.
  • A leading zero means octal. $((010)) = 8, and x=08; $((x)) is an error, value too great for base. That's how date +%m and date +%H break in August, September, and at 8 and 9 o'clock. Write $((10#$x)).
  • An arithmetic error terminates the script. Division by zero or an invalid expression in $((…)) aborts a non-interactive bash entirely, and a || … after it doesn't run. Check the divisor beforehand.
  • ((i++)) with i=0 returns exit code 1. Postfix ++ returns the old value, and 0 is "false". Under set -e the script exits right there. Write ((++i)), i=$((i + 1)) or ((i++)) || true.
  • Overflow without warning. $((2 ** 63)) gives -9223372036854775808. Compute big numbers in python3.
  • expr 3 * 4 without escaping expands * into file names in the current directory and fails with syntax error. Write expr 3 \* 4, or better $((3 * 4)).
  • expr 2+3 without spaces prints the string 2+3, not 5.
  • let without quotes: let x=2 * 3 expands * and breaks. Write let 'x = 2 * 3' or ((x = 2 * 3)).
  • A variable's value is evaluated as an expression. With v='2*3', $((v + 1)) gives 7. Don't let unchecked input into arithmetic — it can be used to execute a command.

See also

variables · conditions-loops · awk · echo-printf · seq · python3