BASH / CHAPTER 04
Integer arithmetic and command status
IntermediateSeparate a numeric result from the success status of an arithmetic command.
By the end of this chapter
- Use arithmetic expansion for values
- Trace arithmetic command exit status
- Validate numeric text before evaluation
The idea
Arithmetic expansion $((expression)) produces a numeric value as text, while the arithmetic command ((expression)) has an exit status based on whether its result is nonzero. The command succeeds for a nonzero result and fails for zero. This can surprise code that uses post-increment: ((n++)) evaluates to the old value, so incrementing an initial zero produces a failure status even though the variable changes.
Bash arithmetic uses fixed-width integers and does not provide arbitrary-precision overflow protection. It also interprets certain numeric spellings specially, including leading-zero forms. Validate expected decimal input before converting it, and keep numeric strings within a stated supported range. Do not insert arbitrary user text into arithmetic expressions as if arithmetic evaluation were a general safe parser for untrusted syntax.
n=0
if ((n++)); then printf 'true\n'; else printf 'false\n'; fi
printf '%s\n' "$n"false 1
Post-increment yields the old zero as the command result, so the conditional fails while n still increases.
Try it yourself
Compare ((n++)) and ((++n)) inside if statements starting from zero.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING