Arithmetic Operations and Math
Performs arithmetic operations using $(( )), let, and expr including integer math, bitwise operations, increment/decrement, and conditional expressions.
Code
#!/usr/bin/env bash
set -euo pipefail
# Basic arithmetic with $(( ))
a=15
b=4
echo "Addition: $(( a + b ))"
echo "Subtraction: $(( a - b ))"
echo "Multiplication: $(( a * b ))"
echo "Division: $(( a / b ))"
echo "Modulo: $(( a % b ))"
echo "Exponent: $(( a ** 2 ))"
# Increment and decrement
x=10
echo "Post-increment: $(( x++ ))"
echo "After: $x"
echo "Pre-increment: $(( ++x ))"
echo "After: $x"
(( x-- ))
echo "After decrement: $x"
# Compound assignment
y=100
(( y += 50 )); echo "y += 50: $y"
(( y -= 30 )); echo "y -= 30: $y"
(( y *= 2 )); echo "y *= 2: $y"
(( y /= 5 )); echo "y /= 5: $y"
# Comparison (returns 1 for true, 0 for false)
echo "a > b: $(( a > b ))"
echo "a == b: $(( a == b ))"
echo "a != b: $(( a != b ))"
# Logical operators
echo "AND: $(( (a > 10) && (b < 5) ))"
echo "OR: $(( (a < 10) || (b < 5) ))"
echo "NOT: $(( !(a < b) ))"
# Bitwise operations
echo "AND: $(( a & b ))"
echo "OR: $(( a | b ))"
echo "XOR: $(( a ^ b ))"
echo "Left shift: $(( a << 2 ))"
echo "Right shift: $(( a >> 2 ))"
# Ternary-like
result=$(( a > b ? 100 : 200 ))
echo "Ternary: $result"
# Random numbers
echo "Random 1-6: $(( RANDOM % 6 + 1 ))"
# Floating point (requires bc)
float_result=$(echo "scale=2; $a / $b" | bc)
echo "Float division: $float_result"
# Sum 1 to 100
sum=0
for n in $(seq 1 100); do
(( sum += n ))
done
echo "Sum 1-100: $sum"How it works
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
What to watch for
- The pipeline is 4 stages deep — when it misbehaves, split the pipe and test the stages separately.
Key statements worth quoting
result=$(( a > b ? 100 : 200 ))
for n in $(seq 1 100); do
(( sum += n ))
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Report a problem with this exampleOpens a pre-filled issue on GitHub.