Arithmetic expansion basics
How it works
Arithmetic expansion uses $((expression)) to produce the result of an integer calculation as text. Use fixed, trusted integer values. Operators such as +, -, *, / and % have arithmetic meanings inside it; parentheses control grouping. Variables can be named without $ inside arithmetic expressions. Division truncates toward zero. Bash uses fixed-width integers and does not check overflow; floating-point arithmetic is not supported. Values with leading zero can be interpreted as octal. Full arithmetic and input validation are covered later.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
Calculate a total
Expected stdout:
24Variable names resolve to integer values inside the expression.
Quotient and remainder
Expected stdout:
21Integer division discards the fractional part; % gives the remainder.
Grouping and precedence
Expected stdout:
1420Multiplication precedes addition unless parentheses change grouping.
Common mistakes
Do not insert arbitrary user strings into arithmetic expressions: Bash can interpret their contents as expressions. Do not treat $((5/2)) as 2.5. Use appropriate numeric tools for decimals.
Practice
With trusted values boxes=4 and items=6, print the total and the remainder when dividing it by 5.
Next: Word splitting and IFS