Bash by Example: Basic Arithmetic
Performing integer arithmetic in Bash using the $((...)) arithmetic expansion syntax, understanding that Bash only supports integer math without floating-point capability, using arithmetic operators for addition, subtraction, multiplication, division and modulo, implementing increment and decrement operations, and using double parentheses for arithmetic evaluation without expansion.
Code
#!/bin/bash
x=10
y=3
# Arithmetic expansion $(( ... ))
sum=$((x + y))
diff=$((x - y))
prod=$((x * y))
div=$((x / y)) # Integer division
mod=$((x % y)) # Modulo (remainder)
exp=$((x ** y)) # Exponentiation
echo "x=$x, y=$y"
echo "Sum: $sum"
echo "Difference: $diff"
echo "Product: $prod"
echo "Division: $div"
echo "Modulo: $mod"
echo "Exponentiation: $exp"
# Increment
((x++))
echo "Incremented x: $x"Explanation
Bash supports integer arithmetic natively using the Arithmetic Expansion syntax: $(( expression )). Inside the double parentheses, you can use standard operators like +, -, *, /, and %. Variable names inside the parentheses do not strictly require the $ prefix, though using it is allowed.
It is important to note that Bash only supports integer arithmetic. Division like 10 / 3 will result in 3, truncating the decimal part. For floating-point math, you must use external tools like bc or awk.
You can also perform arithmetic for side effects (like incrementing a variable) without capturing the result by omitting the leading $, using just (( expression )). This is common for counters in loops.
Code Breakdown
/ is integer division (truncates towards zero) and % gives the remainder.$((x ** y)) performs exponentiation (10 to the power of 3). This operator is available in modern Bash versions.((x++)) is a C-style post-increment. It increases the value of x by 1. Since we don't need the result, we don't use the leading $.echo "Incremented x: $x" prints the updated value. The increment operation modifies the variable in place.
