Integer Arithmetic
+ would only glue strings together.In this page:
Arithmetic Expansion: $(( ))
$(( expression )) evaluates a C-like arithmetic expression and expands to the resulting integer, which can be stored in a variable or used directly in text. Inside $(( )) you can reference variables without a leading $, though using it is also allowed.
Warning: Integer division truncates toward zero: $((7 / 2)) is 3, not 3.5.
Example: Arithmetic Expansion: $(( ))
#!/bin/bash
a=7
b=3
sum=$((a + b))
product=$((a * b))
quotient=$((a / b))
remainder=$((a % b))
echo "sum=$sum product=$product quotient=$quotient remainder=$remainder"
Login to try C/C++/Java/PHP code in the editor
((...)) for Side Effects
The (( expression )) command (no leading $) evaluates the expression purely for its exit status and side effects, such as incrementing a variable, rather than producing output. Its exit status is 0 (true) if the expression evaluates to a non-zero number, and 1 (false) if it evaluates to zero.
Example: ((...)) for Side Effects
#!/bin/bash
count=0
(( count = count + 1 ))
echo "count is now $count"
if (( count > 0 )); then
echo "count is positive"
fi
Login to try C/C++/Java/PHP code in the editor
The let Builtin
let performs arithmetic assignment similarly to $(( )), letting you write let x=x+1 instead of x=$((x + 1)). It is older style and less commonly used in modern scripts, but you will still see it in existing code.
Example: The let Builtin
#!/bin/bash
x=10
let x=x+5
let "x -= 2"
echo "x is now $x"
Login to try C/C++/Java/PHP code in the editor
Increment/Decrement Shortcuts
Inside (( )) or $(( )), Bash supports C-style shortcuts like +=, -=, ++, and -- for updating a variable in place. These are purely arithmetic-context conveniences and do not work the same way outside double parentheses.
Example: Increment/Decrement Shortcuts
#!/bin/bash
score=0
(( score += 10 ))
(( score++ ))
echo "Final score: $score"
Login to try C/C++/Java/PHP code in the editor
- Trying to do math with plain string concatenation, like
total=$a+$b, which just stores the literal text 'a+b' rather than calculating anything. - Forgetting Bash arithmetic is integer-only by default;
$(( 7 / 2 ))gives3, not3.5, because there is no floating-point division built in (you'd needbcorawkfor that). - Using
letwithout realizing its exit status reflects whether the *result* was zero or non-zero, not whether the command syntax succeeded, which can trip up&&/||chains.
$(( expression ))evaluates an arithmetic expression and returns the numeric result as text.((...))(without the leading$) evaluates the expression for its side effects/exit status, commonly used in conditionals and loops.letis an older, less-used way to perform arithmetic assignment, e.g.let x=x+1.- All three forms only support integer math; division truncates toward zero and there is no native floating point.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: