Shell Script by Example: Arithmetic Expansion
Performing integer mathematics in Bash with this code example demonstrating the double-parentheses syntax for arithmetic operations, C-style increment and decrement operators, compound assignment operators, and numeric comparisons in conditional statements.
Code
#!/bin/bash
a=10
b=5
# Arithmetic expansion $((...))
sum=$((a + b))
diff=$((a - b))
prod=$((a * b))
div=$((a / b)) # Integer division
mod=$((a % 3))
echo "Sum: $sum"
echo "Mod: $mod"
# Increment/Decrement (C-style)
((a++))
((b--))
((a+=5))
echo "New a: $a"
# Comparison in arithmetic context
if (( a > 10 )); then
echo "a is greater than 10"
fiExplanation
Bash provides integer arithmetic using the $((expression)) syntax. Inside the double parentheses, you can perform standard mathematical operations including addition, subtraction, multiplication, division, and modulus. Bash only supports integer arithmetic natively; for floating-point calculations, you need external tools like bc or awk. Division always performs integer division, truncating any decimal portion.
The ((expression)) syntax without the leading dollar sign is used for arithmetic operations that have side effects but don't return a value for substitution. Common uses include incrementing variables with ((i++)), decrementing with ((i--)), and compound assignments like ((a += 5)) or ((a *= 2)). This syntax mirrors C-style arithmetic, making it familiar to programmers from other languages.
Within arithmetic expressions, variable names don't strictly require the dollar sign prefix, though it's still valid to use it. The ((...)) construct is also valuable for numeric comparisons in conditional statements. It returns exit status 0 (success) if the expression evaluates to non-zero (true), and exit status 1 (failure) if it evaluates to zero (false). This allows natural numeric comparisons like if (( a > 10 )) without needing the test command's -gt operator.
Code Breakdown
$((a + b)) performs addition and returns the result for assignment.a / b performs integer division, discarding any remainder.((a++)) increments variable in-place using C-style syntax.(( a > 10 )) performs numeric comparison for conditional logic.
