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
| Operator | What it does | Example → 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 : b | ternary 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
| Notation | Value |
|---|---|
0xff / 16#ff | hexadecimal → 255 |
010 / 8#17 | octal (leading zero!) → 8 / 15 |
2#1010 | binary → 10 |
36#z | any base from 2 to 64 → 35 |
10#08 | explicitly 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
| Method | Example | Notes |
|---|---|---|
$((…)) | 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 |
let | let 'n = n * 2' | like ((…)); quote an expression with spaces |
declare -i n | n='3 + 4' → 7 | the variable is always evaluated as an expression |
expr | expr 3 \* 4 | external program; escape *, separate operands and operators with spaces |
awk | awk 'BEGIN { print 7 / 2 }' → 3.5 | fractional numbers and functions sqrt, int, exp, log, sin |
python3 -c | python3 -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))gives3; the remainder is truncated toward zero:$((-7 / 2))→-3. Useawkfor fractions. Multiply before dividing:a * 100 / b, nota / b * 100. - Fractional numbers are a syntax error.
$((3.5 + 1))fails withinvalid arithmetic operator. - A leading zero means octal.
$((010))=8, andx=08; $((x))is an error,value too great for base. That's howdate +%manddate +%Hbreak 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++))withi=0returns exit code 1. Postfix++returns the old value, and 0 is "false". Underset -ethe script exits right there. Write((++i)),i=$((i + 1))or((i++)) || true.- Overflow without warning.
$((2 ** 63))gives-9223372036854775808. Compute big numbers inpython3. expr 3 * 4without escaping expands*into file names in the current directory and fails withsyntax error. Writeexpr 3 \* 4, or better$((3 * 4)).expr 2+3without spaces prints the string2+3, not5.letwithout quotes:let x=2 * 3expands*and breaks. Writelet 'x = 2 * 3'or((x = 2 * 3)).- A variable's value is evaluated as an expression. With
v='2*3',$((v + 1))gives7. 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