Arithmetic Expansion with $((...))
Bash variables hold text, so a=2 and b=3 do not make a + b equal 5 on their own. Arithmetic expansion is the feature that evaluates a mathematical expression and replaces it with the result. You write the expression inside $((...)), and Bash calculates it with whole numbers (integers) before the command runs.
Syntax
$(( expression ))
The expression can contain numbers, variable names, operators and parentheses. Spaces inside the double parentheses are optional.
echo $((2 + 3))
echo $((10 - 4))
echo $((6 * 7))
echo $((17 / 5))
echo $((17 % 5))
echo $((2 ** 10))
Output:
5
6
42
3
2
1024
Each $((...)) was replaced by its value before echo ran. The operators are addition +, subtraction -, multiplication *, division /, remainder % (also called modulo) and exponentiation **.
Spacing makes no difference to the result:
echo $((1+2)) $(( 1 + 2 ))
Output:
3 3
Integer Division and Remainders
Bash arithmetic works only with integers. Division discards the fractional part instead of rounding:
echo $((7 / 2))
echo $((17 / 5))
Output:
3
3
7 / 2 is 3.5 in ordinary mathematics, but Bash returns 3. The remainder operator % gives what is left over, which is why 17 % 5 is 2: five fits into 17 three times, with 2 left.
Negative numbers are truncated toward zero, and the remainder takes the sign of the left operand:
echo $((-17 / 5))
echo $((-17 % 5))
Output:
-3
-2
The remainder is useful for checking even and odd numbers, wrapping a counter around a limit, and splitting values into units.
Using Variables
Inside $((...)), a variable name is replaced by its value, so the dollar sign is optional:
a=8; b=3
echo $((a + b)) $((a * b)) $(($a - $b))
Output:
11 24 5
All three forms work. Writing a without a dollar sign is the usual style inside arithmetic, because it also allows assignment, as the next section shows.
A variable that is unset counts as 0, and text that is not a number is treated as the name of another variable:
unset zz
echo $((zz + 1))
x=y; y=5
echo $((x + 1))
word=abc
echo $((word + 1))
Output:
1
6
1
zz is unset, so it was 0. The variable x holds the text y, which Bash reads as the name of the variable y and looks up to get 5, so the result is 6. The text abc names a variable that does not exist, so it counted as 0, and the answer is 1. This silent behavior is a common source of surprises when a variable contains a word instead of a number.
Assignment and Increment Operators
Arithmetic expansion can change variables as it evaluates. The compound operators +=, -=, *=, /= and %= update a variable, and ++ and -- add or subtract one.
count=5
echo $((count += 2)); echo $count
echo $((count++)); echo $count
echo $((++count)); echo $count
(( count -= 1 )); echo $count
Output:
7
7
7
8
9
9
8
Reading line by line:
count += 2setcountto 7 and produced 7.count++is post-increment. It produced the old value, 7, and then madecountequal to 8.++countis pre-increment. It madecountequal to 9 first and produced 9.(( count -= 1 ))is the command form, which changes the variable without printing a result.countwent from 9 to 8.
Multiple expressions can be joined with a comma. The value of the whole expression is the value of the last one:
echo $((a = 3, b = 4, a * b))
Output:
12
Operator Precedence and Parentheses
Arithmetic follows the usual rules of precedence. Multiplication and division are evaluated before addition and subtraction. Parentheses override the default order.
echo $((2 + 3 * 4))
echo $(((2 + 3) * 4))
Output:
14
20
In the first line, 3 * 4 is calculated first, giving 2 + 12. In the second line, the parentheses force 2 + 3 to be calculated first. Notice that $((( has three opening parentheses: the first two start the arithmetic expansion, and the third is an ordinary grouping parenthesis.
Comparison, Logic and the Ternary Operator
Comparison operators work on numbers and return 1 for true and 0 for false:
echo $((5 > 3)) $((5 < 3)) $((5 == 5)) $((5 != 5))
echo $((1 && 0)) $((1 || 0)) $((!0))
Output:
1 0 1 0
0 1 1
This is the reverse of shell exit statuses, where 0 means success. Inside arithmetic, the convention follows the C language: zero is false and any non-zero value is true.
The ternary operator condition ? value_if_true : value_if_false chooses between two values:
n=7
echo $(( n % 2 == 0 ? 0 : 1 ))
Output:
1
The condition n % 2 == 0 is false for 7, so the expression produced the value after the colon.
Bitwise Operators
Bash supports the operators that work on the binary digits of integers:
echo $((5 & 3)) $((5 | 3)) $((5 ^ 3)) $((~5)) $((1 << 4)) $((256 >> 2))
Output:
1 7 6 -6 16 64
These are AND &, OR |, exclusive OR ^, bitwise NOT ~, left shift << and right shift >>. Shifting left by 4 multiplies by 2 four times, so 1 << 4 is 16. Shifting right by 2 divides 256 by 4. Bit operators appear in permission calculations, flags and low-level scripts.
Numbers in Other Bases
Bash reads a number's base from its prefix:
echo $((0x1F)) $((010)) $((2#1010)) $((16#ff)) $((10#010))
Output:
31 8 10 255 10
| Written as | Base | Meaning |
|---|---|---|
0x1F | 16 (hexadecimal) | 0x prefix |
010 | 8 (octal) | leading zero |
2#1010 | 2 (binary) | base#digits form |
16#ff | 16 | any base from 2 to 64 |
10#010 | 10 | forces decimal |
The leading zero rule catches many people out. 010 is eight, not ten, and a number such as 08 is an error because 8 is not an octal digit:
echo $((08))
Output:
script.sh: line 3: 08: value too great for base (error token is "08")
When the digits come from user input or a date, remove the ambiguity by forcing base 10:
n=08
echo $((10#$n + 1))
Output:
9
10#$n expands to 10#08, which is read as decimal 8.
The (( )) Command and Exit Status
Without the dollar sign, (( expression )) is a command that evaluates the expression and uses its truth value as an exit status. It succeeds (status 0) when the result is non-zero and fails (status 1) when the result is zero.
if (( 5 > 3 )); then echo yes; fi
(( 0 )); echo "status for (( 0 )): $?"
(( 7 )); echo "status for (( 7 )): $?"
Output:
yes
status for (( 0 )): 1
status for (( 7 )): 0
This form is the natural choice in if and while conditions that compare numbers, because it uses the familiar <, > and == operators and does not need $ signs on variable names.
Two older alternatives are worth recognizing:
let "z = 4 * 5"; echo $z
declare -i num
num=3+4
echo $num
Output:
20
7
let evaluates its arguments as arithmetic. A variable declared with declare -i is an integer variable, so Bash evaluates anything assigned to it as arithmetic: num=3+4 stored 7, not the text 3+4.
Whole Numbers Only
The most important limit of Bash arithmetic is that it has no decimals. Writing a decimal number produces an error:
echo $((3.5 + 1))
Output:
script.sh: line 3: 3.5 + 1: syntax error: invalid arithmetic operator (error token is ".5 + 1")
For decimal calculations, hand the work to another tool. bc is a calculator that accepts a setting named scale for the number of decimal places, and awk includes floating-point math:
echo "scale=2; 7 / 2" | bc
awk 'BEGIN { printf "%.2f\n", 7 / 2 }'
Output:
3.50
3.50
bc and awk are separate programs that may not be installed on every minimal system.
Errors and Limits
Division by zero stops the expression with an error and a non-zero exit status:
echo $((5 / 0))
Output:
script.sh: line 3: 5 / 0: division by 0 (error token is "0")
Other invalid input also reports an error instead of guessing:
word2="hello world"
echo $((word2 + 1))
s=12abc
echo $((s + 1))
echo $((2 ** -1))
Output:
script.sh: line 3: hello world: syntax error in expression (error token is "world")
script.sh: line 5: 12abc: value too great for base (error token is "12abc")
script.sh: line 6: 2 ** -1: exponent less than 0 (error token is "1")
Integers have a fixed size. On a 64-bit system, the largest value is 9223372036854775807, and one more wraps around to a large negative number without any warning:
echo $((9223372036854775807))
echo $((9223372036854775807 + 1))
Output:
9223372036854775807
-9223372036854775808
Arithmetic in Strings and Array Indexes
Because $((...)) is an expansion, it works inside double quotes:
echo "Total: $((3 * 4)) items"
Output:
Total: 12 items
Array subscripts are evaluated as arithmetic too, so no $((...)) is needed there, although it is allowed:
arr=(a b c d)
i=1
echo "${arr[i+1]}"
echo "${arr[$((i+2))]}"
Output:
c
d
Practical Examples
Calculate a total, an average and a remainder in a loop:
sum=0
for n in 10 20 35; do sum=$((sum + n)); done
echo "sum=$sum avg=$((sum / 3)) remainder=$((sum % 3))"
Output:
sum=65 avg=21 remainder=2
The loop added each number to sum. The average is whole-number division, so 65 / 3 became 21, and the remainder 2 shows what was lost.
Convert a number of seconds into hours, minutes and seconds:
secs=3725
printf '%02d:%02d:%02d\n' $((secs/3600)) $((secs%3600/60)) $((secs%60))
Output:
01:02:05
The expression secs/3600 gives whole hours (1). secs%3600 removes the hours, leaving 125 seconds, and dividing by 60 gives whole minutes (2). secs%60 is the leftover seconds (5). The %02d format in printf pads each number with a leading zero to two digits.
Roll a dice with the built-in RANDOM variable, which produces a different whole number from 0 to 32767 each time it is read:
r=$((RANDOM % 6 + 1))
(( r >= 1 && r <= 6 )) && echo "dice in range"
Output:
dice in range
RANDOM % 6 gives a value from 0 to 5, and adding 1 shifts it to the range 1 to 6. The second line confirms the result is in range, so the printed text is the same on every run even though the dice value changes.