Evaluating an expression
When bash meets $((, it reads everything up to the matching )) as an arithmetic expression. The expression is evaluated, and the decimal result replaces the whole construct. Inside the expression you can write variable names without a dollar sign, which is the main readability advantage over the older expr program. A variable that is unset or empty counts as zero, so an expression can refer to a name before it has been given a value.
echo $(( (7 + 5) * 3 ))
n=4
echo $(( n * n + 1 ))36
17The arithmetic step is one of the expansions covered in the order lesson. It runs after parameter expansion, so the value of a variable is available by the time the arithmetic is evaluated. Because the result is text again, you can pass it to a command or store it in another variable like any other value.
Operators you already know
The operators follow C conventions. You have addition, subtraction, multiplication, division, and remainder. The exponent operator ** raises a number to a power. Comparisons such as <, >=, ==, and != produce 1 when they are true and 0 when they are false, so you can use them as numbers. Logical operators, bitwise operators, the conditional operator ?:, and the assignment operators such as += are all available. The increment and decrement operators work too, although in a bare statement they are easier to read with the arithmetic command, which is covered below.
echo $(( 2 ** 10 ))
echo $(( 5 > 3 ))
echo $(( 5 < 3 ))
echo $(( 6 & 3 ))1024
1
0
2Remember that the comparison results are numbers, not words. The expression $(( 5 > 3 )) prints 1, and a script can add it to a total without any test command.
Division and remainder truncate toward zero
Integer division discards the fraction. The result is rounded toward zero, not down toward negative infinity. So $(( 17 / 5 )) is 3, and $(( -7 / 2 )) is -3, not -4. The remainder follows the sign of the dividend, so $(( -7 % 3 )) is -1. Those rules match C, and they are the reason a floor-style calculation must be written by hand when negative numbers can appear. Dividing by zero is an error, and bash reports it and stops the expansion. Test the divisor first in a script that might receive zero.
Bases and leading zeros
Bash accepts numbers in several bases. The form base#digits reads digits in that base, so 16#ff is 255 and 2#1010 is 10. A number that starts with a zero is read as octal, which is a trap for values such as dates and zero-padded counters. The expression $(( 010 )) is 8, not 10. Bash also accepts the prefix 0x for hexadecimal, so $(( 0x1f )) is 31. When you format numbers that have leading zeros, write them in a form that is not read as octal, or use the base prefix explicitly.
echo $(( 16#ff )) $(( 010 )) $(( 0x1f ))255 8 31The arithmetic command
When an arithmetic expression is the whole command, use double parentheses without the leading dollar sign. The command exits with status 0 when the result is nonzero, and with status 1 when the result is zero. That makes it a natural condition in an if statement or with &&. The arithmetic command can also assign variables and change them with increment operators, which avoids the dollar sign on the left side of an assignment.
i=0
(( i++ ))
(( i < 3 )) && echo "still small: $i"still small: 1Arithmetic in a loop
The most common use of arithmetic expansion is a counter or a running total inside a loop. Because the expansion is performed by the shell, the loop does not start any process for each addition. The example below adds three numbers from a list and prints the total, and it shows that the variables inside the expression are read by name without any dollar sign on the left side of the assignment.
total=0
for n in 1 2 3; do
total=$(( total + n ))
done
echo "$total"6The line total=$(( total + n )) has the dollar sign only on the outside of the expansion. Inside the parentheses, both names refer to the current values. If you forget the outer assignment and write only the expression, nothing is stored and the total never changes, which is a quiet bug that the lab for this lesson can help you avoid.
Compared with expr and let
Older scripts often use the expr program for arithmetic. It is an external command, so each call starts a process, and it needs spaces around every operator and a backslash before the multiplication sign so that the shell does not expand the star as a glob. The equivalent of expr 3 \* 4 is simply $(( 3 * 4 )). The let builtin is a second option that evaluates an expression without the dollar sign, and it sets its exit status from the last value, which is 1 when that value is zero. Both forms are valid bash, but the arithmetic expansion is the one that reads most clearly in new code.
What bash arithmetic cannot do
Bash arithmetic works on integers only, and the largest value is the width of a machine integer. It has no floating-point numbers, so $(( 7 / 2.0 )) is a syntax error. For fractions, reach for a tool such as awk, which is installed in the lab and handles decimal arithmetic. The expansion also does not read files or run commands, so it cannot count lines in a file. Combine it with command substitution when you need a value from outside the shell, such as total=$(( $(wc -l < list.txt) * 2 )).
The biggest practical advantage is speed. An arithmetic expansion runs inside the shell without starting a process, so a loop that adds a few hundred numbers is quick. Use it whenever the values are integers, and reach for another tool when the values are not.