Do math in Bash: integer arithmetic with $(( )), increment counters, compare numbers, and reach for bc or awk when you need decimals.
Why: Bash does integer arithmetic inside $(( )). Inside the double parentheses you do NOT need $ on variable names. The usual operators work: + - * / and % (remainder).
#!/usr/bin/env bash
a=7
b=2
echo "$(( a + b ))" # 9
echo "$(( a * b ))" # 14
echo "$(( a / b ))" # 3 (integer division — no decimals)
echo "$(( a % b ))" # 1 (remainder)Why: (( )) on its own evaluates an arithmetic expression and can mutate variables — perfect for loop counters. ((count++)) increments in place; ((total += n)) accumulates.
#!/usr/bin/env bash
count=0
for _ in 1 2 3 4; do
(( count++ ))
done
echo "count is $count" # 4
total=0
for n in 10 20 30; do
(( total += n ))
done
echo "total is $total" # 60Why: Bash only does integers. For decimals, pipe an expression into bc with -l (load the math library). scale= sets how many decimal places to keep.
3 / 2 with two decimal places
echo "scale=2; 3 / 2" | bc # 1.50Use bc -l for the math library (pi, sqrt, etc.)
echo "sqrt(2)" | bc -l # 1.41421356...Why: when numbers come from a file or a pipeline, awk both extracts columns and does floating-point math in one step — often simpler than wrangling bc. Note: awk is covered more fully in the Linux course lesson on pipes & text processing.
Sum the second column of a CSV
awk -F',' '{ sum += $2 } END { print sum }' data.csvAverage it, to two decimals
awk -F',' '{ s += $2; n++ } END { printf "%.2f\n", s / n }' data.csv