patternbashModerate
Arithmetic evaluation: (( )) and $(( )) for numeric operations
Viewed 0 times
arithmeticintegernumericdouble parenletexprincrementmodulo
Problem
Bash is string-based; arithmetic requires special syntax. Using expr or test -eq is clunky. Developers mix up (( )) for evaluation and $(( )) for substitution.
Solution
Use (( )) for arithmetic conditionals and side-effecting operations. Use $(( )) when you need the numeric result as a value.
# Conditional arithmetic
(( count > 0 )) && echo positive
# Increment
(( i++ ))
(( total += 5 ))
# Substitution
result=$(( a * b + c ))
echo "$(( 2 ** 10 ))" # 1024
# C-style for loop
for (( i=0; i<10; i++ )); do echo $i; done
# Conditional arithmetic
(( count > 0 )) && echo positive
# Increment
(( i++ ))
(( total += 5 ))
# Substitution
result=$(( a * b + c ))
echo "$(( 2 ** 10 ))" # 1024
# C-style for loop
for (( i=0; i<10; i++ )); do echo $i; done
Why
(( )) creates an arithmetic context where variables don't need $ prefix and the exit code is 1 if the expression is zero (falsy). $(( )) substitutes the numeric result of the expression into the command.
Gotchas
- (( 0 )) returns exit code 1 (falsy) — set -e will exit if you write '(( var-- ))' when var was 1
- All arithmetic is integer-only in bash; use bc or awk for floating point
- $(( )) does not require quoting — it always produces a single word with no spaces
- Variables inside (( )) can be written without $ but with $ also works
- Avoid 'let' — (( )) is the modern equivalent and clearer
Code Snippets
Arithmetic evaluation in bash
a=10 b=3
# Arithmetic substitution
echo $(( a + b )) # 13
echo $(( a % b )) # 1
echo $(( 2 ** 8 )) # 256
# Arithmetic conditional
if (( a > b )); then echo "$a is bigger"; fi
# Increment/decrement
count=0
(( count++ )) # now 1
(( count += 5 )) # now 6
# C-style for loop
for (( i=1; i<=5; i++ )); do
echo "Item $i"
done
# Floating point: use bc
result=$(echo "scale=2; 10/3" | bc)Context
Counter loops, numeric comparisons, index calculations in bash scripts
Revisions (0)
No revisions yet.