Arithmetic commands and status
(( expression )) evaluates arithmetic as a command. It produces no normal output by itself. A nonzero expression value means exit status 0 (success); a zero value means status 1. This is different from $(( expression )), which substitutes a number. The builtin let evaluates arithmetic arguments with the same zero/nonzero rule for the final expression. Quote its arguments to keep spaces and operators from being interpreted as shell syntax. Assignments such as (( count += 2 )) change the variable. count++ yields the old value before increasing it; ++count increases it and yields the new value. Save $? immediately. A zero result is not necessarily a calculation error. Later error-handling lessons will show why this matters when automatic exit-on-error is enabled. These status examples assume automatic exit on error is disabled. To increment a trusted counter without treating its old zero value as a failing arithmetic command, use count=$(( count + 1 )).
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale; the fractional lesson requires awk. Output is shown separately; do not enter it as code.
Arithmetic in a condition
stock=8if (( stock >= 5 )); then printf '%s\n' readyelse printf '%s\n' lowfiExpected stdout:
readyThe comparison yields 1, so the arithmetic command succeeds.
Compare increment forms
count=0(( count++ ))status=$?printf '%s %s\n' "$count" "$status"count=0(( ++count ))status=$?printf '%s %s\n' "$count" "$status"Expected stdout:
1 11 0Both increment count; the expression values and statuses differ.
Use let with quoted expressions
count=3let 'count = count - 3'status=$?printf '%s %s\n' "$count" "$status"Expected stdout:
0 1The assignment succeeds as a calculation but the zero expression value yields status 1.
Common mistakes
(( count++ )) with count initially zero still increments it, but returns status 1. Do not interpret that status as proof that no update happened.
Practice
Set count to 0; run a postfix increment and capture its status. Reset count and repeat with prefix increment. Predict both final values and statuses before running.
Next: Arithmetic operators and precedence