Arithmetic Evaluation and Integer Math

Arithmetic Evaluation and Integer Math in Bash: --- On the desk of a pre-electronic accounts office sits a mechanical adding machine: a heavy box of gears and…


The Analogy: The Mechanical Adding Machine

On the desk of a pre-electronic accounts office sits a mechanical adding machine: a heavy box of gears and levers with a row of number wheels across the top. You enter a figure on the keys, pull the handle, and the wheels turn to show the running total. It is a marvel of engineering, but it has three hard limits built into its metal, and every clerk who used one knew them by heart. Bash arithmetic is that machine: fast, reliable, and bounded by exactly the same three limits.

The first limit is that the wheels only show whole numbers. There is no wheel for tenths; the machine counts pennies, not fractions of a penny. If a calculation would land between two whole numbers, the machine simply does not represent the in-between -- it stops at a whole number and the fraction is gone. Bash is identical: $(( 7 / 2 )) is 3, not 3.5, because there is no wheel for the half. Every division truncates, dropping whatever was after the decimal point, and it truncates toward zero so -7 / 2 is -3, not -4.

The second limit is that the row of wheels has a fixed width. A machine with sixteen wheels can show a total up to a certain size, and if you keep adding past the last wheel's capacity, the wheels roll over -- like a car odometer clicking from all nines back to zeros -- and the total shown is suddenly, silently wrong. Bash uses a fixed-width signed integer, sixty-four bits wide, and when a total climbs past the top it wraps around to the most negative value with no warning at all. The machine does not jam or ring a bell; it just shows a wrong number as confidently as a right one.

The third limit is the failure mode that catches people: the machine does exactly what the gears dictate, even when that is not what you meant. A clerk who wanted an average and divided 393 by 5 got 78 on the wheels, wrote 78 in the ledger, and never saw the 0.6 that fell off the edge. Nobody was warned, because from the machine's point of view nothing went wrong -- 78 is the honest whole-number answer. The whole discipline of integer arithmetic in the shell is knowing when truncation and wraparound will bite, and reaching for scaled integers or an external tool at exactly those moments, because bash will never tell you the fraction mattered.


Syntax or Core Structure

Bash has two spellings for arithmetic. $(( expression )) expands to the numeric result and is used wherever you want a value. (( expression )) runs as a command, setting an exit status but producing no output, and is used for tests and assignments. Inside either, you write ordinary infix math with C-style operators.

#!/usr/bin/env bash
a=7 b=2
printf 'sum:       %d\n' "$(( a + b ))"
printf 'diff:      %d\n' "$(( a - b ))"
printf 'product:   %d\n' "$(( a * b ))"
printf 'quotient:  %d\n' "$(( a / b ))"
printf 'remainder: %d\n' "$(( a % b ))"
printf 'power:     %d\n' "$(( a ** b ))"

# division truncates toward zero, and so does the sign of the remainder
printf 'trunc 7/2 = %d, -7/2 = %d\n' "$(( 7 / 2 ))" "$(( -7 / 2 ))"
printf 'mod  7%%2 = %d, -7%%2 = %d\n' "$(( 7 % 2 ))" "$(( -7 % 2 ))"

Note that variables inside $(( )) do not need a leading $ -- the arithmetic context reads bare names as numbers. The %% in the last printf format is how you write a literal percent sign in a format string, not an arithmetic operator.

Output:

sum:       9
diff:      5
product:   14
quotient:  3
remainder: 1
power:     49
trunc 7/2 = 3, -7/2 = -3
mod  7%2 = 1, -7%2 = -1

Technical Depth: Operators, Bases, and the Two Silent Traps

The operator set, by precedence

Arithmetic in bash follows C's operators and C's precedence. The table lists them from highest binding to lowest; when in doubt, parenthesise, because a misremembered precedence is a silently wrong answer, not an error.

GroupOperatorsNotes
unary+ - ! ~negation, logical not, bitwise not
exponent**right-associative
multiplicative* / %integer divide truncates toward zero
additive+ -
shift<< >>multiply or divide by powers of two
relational< <= > >=yield 1 or 0
equality== !=yield 1 or 0
bitwise& ^ then barand, xor, or
logical&& then double-barshort-circuit, yield 1 or 0
ternary? :C conditional expression
assignment= += -= *= /= %= &= etcthe whole family

Number bases: reading is easy, writing is manual

Bash reads several bases on input. A leading 0x is hex, a leading 0 is octal, and the general form base#number accepts any base from 2 to 64. The catch that bites shell authors is octal: a zero-padded value like 08 is not eight, it is an error, because 8 is not a valid octal digit.

#!/usr/bin/env bash
printf 'hex 0xff      = %d\n' "$(( 0xff ))"
printf 'octal 010     = %d\n' "$(( 010 ))"
printf 'binary 2#1010 = %d\n' "$(( 2#1010 ))"
printf 'base36 z      = %d\n' "$(( 36#z ))"

x=12 y=10
printf 'and  12 & 10 = %d\n' "$(( x & y ))"
printf 'or   12 | 10 = %d\n' "$(( x | y ))"
printf 'xor  12 ^ 10 = %d\n' "$(( x ^ y ))"
printf 'shl  12 << 1 = %d\n' "$(( x << 1 ))"
printf 'shr  12 >> 1 = %d\n' "$(( x >> 1 ))"

Output:

hex 0xff      = 255
octal 010     = 8
binary 2#1010 = 10
base36 z      = 35
and  12 & 10 = 8
or   12 | 10 = 14
xor  12 ^ 10 = 6
shl  12 << 1 = 24
shr  12 >> 1 = 6

Bash reads bases but does not write them: there is no $(( )) form that outputs hex or binary. For that you use printf '%x' or printf '%o'. The bit operations are the practical reason to care about bases: 12 & 10 is 8 because only the 8-bit is set in both, and 12 << 1 is 24 because a left shift by one doubles.

Assignment operators and increment

Inside (( )) you have the full C family of compound assignments and both the pre- and post-increment forms. Post-increment yields the old value then increments; pre-increment increments then yields the new value.

#!/usr/bin/env bash
n=5
printf 'n++ yields %d then n is %d\n' "$(( n++ ))" "$n"
printf '++n yields %d then n is %d\n' "$(( ++n ))" "$n"
(( n += 10 )); printf 'after += 10, n = %d\n' "$n"
(( n *= 2 ));  printf 'after *= 2,  n = %d\n' "$n"

Output:

n++ yields 5 then n is 6
++n yields 7 then n is 7
after += 10, n = 17
after *= 2,  n = 34

Starting from 5, n++ returns 5 and leaves n at 6; ++n then returns 7 and leaves n at 7. From there += 10 gives 17 and *= 2 gives 34. One caution: (( n++ )) as a standalone command when n starts at 0 returns exit status 1, because the value yielded is 0 and (( maps a zero result to failure -- a subtle way set -e can abort a script on a harmless increment.

The two silent traps: truncation and overflow

The first trap is that division discards the fraction. The second is that a signed 64-bit total wraps when it overflows, with no diagnostic.

#!/usr/bin/env bash
max=9223372036854775807
printf 'max        = %d\n' "$max"
printf 'max + 1    = %d\n' "$(( max + 1 ))"

# a naive average loses its fraction
readings="71 74 92 68 88"
sum=0 count=0
for r in $readings; do sum=$(( sum + r )); count=$(( count + 1 )); done
printf 'sum %d over %d = %d (real average is 78.6)\n' \
  "$sum" "$count" "$(( sum / count ))"

Output:

max        = 9223372036854775807
max + 1    = -9223372036854775808
sum 393 over 5 = 78 (real average is 78.6)

The max + 1 line shows the odometer rollover: one past the largest positive value is the most negative value. The average line shows truncation: 393 divided by 5 is 78.6, but the wheels show 78 and the 0.6 is gone. The fix for the fraction is scaled integer math -- multiply by 10 or 100 before dividing, then split the result -- which the real-world example uses to recover one decimal place.


Real World Example: A Packing Calculator With One Decimal Place

Warehouse and shipping code lives on integer arithmetic: how many boxes hold this many items, how full is the last box, what percentage is that. This calculator answers all three using two techniques the lesson has built toward -- ceiling division with the (a + b - 1) / b idiom, and scaled-integer math to show one decimal place without any floating point.

#!/usr/bin/env bash
# pack.sh -- integer-only packing and capacity math
set -u

# ceiling division without floats: rounds up when there is any remainder
boxes_needed() {
  local items=$1 cap=$2
  printf '%d' "$(( (items + cap - 1) / cap ))"
}

report() {
  local items=$1 cap=$2 boxes last pct tenths
  boxes=$(boxes_needed "$items" "$cap")
  # items in the last box: the remainder, or a full box when it divides evenly
  last=$(( items % cap ))
  (( last == 0 )) && last=$cap
  # percent full, truncated, then one decimal via scale-by-1000
  pct=$(( last * 100 / cap ))
  tenths=$(( last * 1000 / cap % 10 ))
  printf '%5d items / cap %2d -> %3d boxes, last holds %2d (%d.%d%% full)\n' \
    "$items" "$cap" "$boxes" "$last" "$pct" "$tenths"
}

report 100 12
report 96 12
report 1 12
report 250 25
report 7 3

Output:

  100 items / cap 12 ->   9 boxes, last holds  4 (33.3% full)
   96 items / cap 12 ->   8 boxes, last holds 12 (100.0% full)
    1 items / cap 12 ->   1 boxes, last holds  1 (8.3% full)
  250 items / cap 25 ->  10 boxes, last holds 25 (100.0% full)
    7 items / cap  3 ->   3 boxes, last holds  1 (33.3% full)

Trace the first row. One hundred items in boxes of twelve: (100 + 12 - 1) / 12 is 111 / 12, which truncates to 9 -- the ceiling, because the +11 pushes any non-zero remainder up over the next integer boundary. The last box holds 100 % 12, which is 4. The percentage is 4 * 100 / 12, truncating to 33, and the decimal comes from 4 * 1000 / 12 % 10: that is 333 % 10, giving 3, so the display reads 33.3 without a single floating-point operation.

The 96-item row shows the even-division guard working: 96 % 12 is 0, so the code resets last to a full 12 rather than reporting an empty last box, and the percentage comes out 100.0. Watch how the scale-by-1000 trick generalises: multiplying before dividing preserves the digits that truncation would otherwise discard, and the modulo peels off exactly the digit you want. This is the standard shell idiom for fixed-point display.

The honest limits include two real defects. First, the decimal is truncated, not rounded: a true 91.67% prints as 91.6, because % 10 takes the tenths digit and throws away everything below it, so the calculator consistently reads low on the fraction. Second, and more serious, cap of zero is unguarded -- boxes_needed 10 0 evaluates (10 + 0 - 1) / 0 and bash aborts the whole script with a "division by 0" error and a non-zero exit, so a single bad capacity in a data feed takes down the run. A production version would reject a non-positive cap before dividing, and would round the last digit by adding half the divisor before the final division.


Common Mistakes

  1. Expecting division to keep the fraction. $(( 7 / 2 )) is 3, not 3.5, and $(( 1 / 2 )) is 0. Every division truncates toward zero. When you need a fraction, scale up first ($(( 7 * 100 / 2 )) gives 350, meaning 3.50) or use awk, bc, or printf for real decimals.
  1. Zero-padding a number and hitting the octal trap. A value like 08 or 09 inside $(( )) is an error, because a leading zero means octal and 8 and 9 are not octal digits. Strip the leading zero, or force base ten with $(( 10#08 )), which is common when parsing zero-padded dates or times.
  1. Ignoring overflow past 64 bits. Bash integers are signed 64-bit, so a running total or a factorial that climbs past about 9.2 quintillion wraps silently to a negative number. There is no warning; if your values can get that large, do the math in a tool with big integers.
  1. Letting (( expr )) abort under set -e. A standalone (( count++ )) when count is 0 yields a zero result, which (( reports as exit status 1, so set -e kills the script. Use count=$(( count + 1 )) or append || true when the arithmetic value could legitimately be zero.
  1. Quoting arithmetic so it becomes a string. Writing n="$n + 1" sets n to the literal text 5 + 1, not 6. Assignment arithmetic must happen inside (( )) or $(( )); the plain = never evaluates math.
  1. Forgetting that comparison operators yield 1 or 0. $(( a > b )) is a number, 1 or 0, not a branch. That is useful for counting how many conditions hold, but if you meant to branch, use (( a > b )) as a command in an if, not its expanded value.
  1. Assuming precedence instead of parenthesising. $(( 2 + 3 * 4 )) is 14, not 20, and $(( a & b == c )) binds the == first because equality outranks bitwise-and. When mixing bitwise and comparison operators, parenthesise; the cost is nothing and the bug is silent.
  1. Reusing a remainder's sign carelessly. $(( -7 % 2 )) is -1, not 1, because the result takes the sign of the dividend. Code that assumes a modulo is always non-negative -- for indexing into a ring buffer, say -- breaks on negative inputs.
  1. Treating the last box as empty when it divides evenly. items % cap is 0 when the count fills the last box exactly, so a naive "last box holds the remainder" reports 0 instead of a full box. Guard the zero case and reset it to a full capacity, as the packing example does.

Best Practices

  • Scale before dividing to keep decimals. To show N decimal places, multiply by ten-to-the-N before the division, then split the integer and fractional parts with division and modulo. This gives fixed-point output with no floating-point dependency.
  • Use the (a + b - 1) / b idiom for ceiling division. It rounds up whenever there is any remainder and reduces to plain division when there is not, all in integer math. It is the canonical way to answer "how many containers do I need".
  • Force base ten when parsing zero-padded fields. Dates, times, and zero-padded counters can carry leading zeros that trigger the octal trap. Wrap such values as 10#$value inside arithmetic so 08 and 09 parse as eight and nine.
  • Guard divisors before dividing. A zero divisor aborts the whole script with a division-by-zero error. Check that a capacity, count, or rate is positive before using it as a denominator, and return a clear error otherwise.
  • Prefer n=$(( n + 1 )) over a bare (( n++ )) under set -e. The assignment form always succeeds, sidestepping the zero-result exit-status trap that can abort an errexit script on an ordinary increment.
  • Parenthesise mixed-operator expressions. Relying on remembered precedence between bitwise, comparison, and arithmetic operators is a reliable source of silent bugs. Explicit parentheses document intent and cost nothing at runtime.
  • Reach for bc or awk when you genuinely need real numbers. Bash integer math is the right tool for counts and indices, but currency, rates, and scientific values want true decimals. Know where the integer boundary is and step outside it deliberately.
  • Watch the 64-bit ceiling on accumulating totals. When summing large byte counts or multiplying repeatedly, estimate whether the result can exceed the signed 64-bit range, and switch tools before it wraps rather than after.

Practice Exercises

  1. A fixed-point percentage function. Write a function that takes a part and a whole and prints the percentage to two decimal places using only integer arithmetic -- scale by 10000, then split with division and modulo. Test it on 1 out of 3 and confirm it prints 33.33, and note in a comment where the value is truncated rather than rounded.
  1. A rounding ceiling divide. Implement two functions, one that floor-divides and one that rounds to nearest (by adding half the divisor before dividing), and print both results for 7 over 2, 8 over 3, and 10 over 4. Explain in a comment why (a + b/2) / b rounds and (a + b - 1) / b ceilings.
  1. A base converter. Read a decimal number and print it in hex, octal, and binary. Hex and octal come straight from printf; for binary, write a loop that peels off bits with % 2 and / 2 and assembles the digits. Verify against $(( 2#... )) that your binary string round-trips back to the original number.
  1. Overflow detection. Write a script that multiplies a running total by successive integers and stops when the result would exceed the 64-bit maximum. Detect the impending overflow before it happens by comparing against max / next, and print the largest factorial that fits, explaining in a comment why checking after the multiply would be too late.