iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Arithmetic

Bash arithmetic: \$((...)) , let, expr, floating point with bc / awk. The patterns for counting and math in shell.

Linux — Bash arithmetic

EXAMPLE
# ===== Integer arithmetic with $((...)) =====
a=5
b=3
echo $((a + b))     # 8
echo $((a * b))     # 15
echo $((a / b))     # 1 (integer division)
echo $((a % b))     # 2
echo $((a ** 2))    # 25
echo $((a << 1))    # 10 (left shift)
echo $((a & b))     # 1 (bitwise AND)
echo $((-a))        # -5

# Comparison returns 0 (false) or 1 (true):
echo $((5 > 3))     # 1
echo $((5 == 3))    # 0

# In place:
((a += 1))         # a=6
((a++))            # post-increment
((--a))            # pre-decrement
((a > b)) && echo 'a is bigger'

# ===== let (older style) =====
let c=5+3
let "d = a * b"

# ===== expr (POSIX, legacy) =====
n=$(expr 5 + 3)    # spaces matter; * must be quoted

# Avoid unless you need POSIX strict shells.

# ===== Floating point with bc =====
result=$(echo 'scale=2; 5 / 3' | bc)
echo $result        # 1.66

# bc inline:
echo "scale=4; sqrt(2)" | bc -l   # 1.4142

# ===== Floating point with awk =====
echo | awk 'BEGIN { printf "%.2f\n", 5 / 3 }'

# ===== printf for formatting =====
printf '%.3f\n' $(echo 'scale=10; 22/7' | bc)
printf '%d files\n' 12345
printf '%05d\n' 42       # 00042 (padded)

# ===== Common patterns =====
# Sum a column of numbers:
total=$(awk '{ s += $1 } END { print s }' nums.txt)

# Average:
avg=$(awk '{ s += $1; n++ } END { print s / n }' nums.txt)

# Percentage:
echo $((100 * 23 / 50))    # 46

# Loop with counter:
for i in {1..10}; do
  echo "$((i * i))"
done

# Sleep with random jitter:
sleep $((RANDOM % 5 + 1))    # 1-5 seconds

# ===== Caveats =====
# Bash arithmetic is INTEGER only.
# - 5 / 3 = 1 (not 1.66)
# - For float: bc, awk, or Python / Node

# Integer overflow at 64-bit boundary (signed).

# ===== Patterns to internalise =====
# - $((...)) for integer math
# - bc for floats
# - awk for column math on files
# - printf for formatting
# - ((var++)) for in-place updates

# ===== Pitfalls =====
# - expr is slow + cryptic
# - 5/3 returns 1 in shell unless you use bc/awk
# - Forgetting -l on bc for math library (sin, sqrt)
# - Locale-dependent decimal separators (1,5 vs 1.5)

Why it matters

Bash arithmetic: \$((...)) for integers, bc for floats, awk for file column math. expr is legacy. Most scripts only need integer math; reach for bc / awk when floats matter. The patterns are tiny but show up daily in ops + analytics one-liners.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
x=5
((x++))
let y=x*3
result=$((x + y))
Try it Yourself »

Discussion

Loading…