Arithmetic Operations and Math

Performs arithmetic operations using $(( )), let, and expr including integer math, bitwise operations, increment/decrement, and conditional expressions.

BashCli Tooling

Code

snippet
#!/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

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.