Arithmetic operators and precedence
Operator precedence determines which operations bind more tightly. Multiplication, division and remainder bind more tightly than addition and subtraction. Parentheses explicitly group operations. Bash also supports exponentiation **, comparisons (yielding integer 1 or 0), logical !, &&, ||, bitwise ~, &, ^, |, shifts << and >>, and conditional condition ? yes : no. Bitwise operations work on individual bits: for example, 6 (binary 110) AND 3 (011) gives 2 (010). Logical operators test whether values are zero or nonzero; && and || short-circuit. Assignment operators such as += combine a calculation with an update. The comma operator evaluates expressions in sequence and yields the last value. When mixing operators, use parentheses for clarity. Arithmetic operators here are inside an arithmetic context, not shell redirections or pipelines. Use small nonnegative values for bit operations in this beginner lesson.
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.
Group calculations
printf '%s\n' "$(( 2 + 3 * 4 ))" "$(( (2 + 3) * 4 ))" "$(( 2 ** 3 ))"Expected stdout:
14208Parentheses change grouping; ** raises a number to a power.
Bitwise versus logical
printf '%s\n' "$(( 6 & 3 ))" "$(( 6 && 3 ))" "$(( 3 << 1 ))"Expected stdout:
216Bitwise AND combines bits, logical AND tests nonzero values, and a left shift moves bits.
Select a bounded value
limit=10count=14count=$(( count > limit ? limit : count ))(( count += 2 ))printf '%s\n' "$count"Expected stdout:
12The conditional chooses 10; the compound assignment adds 2.
Common mistakes
2 + 3 * 4 is 14, not 20. Do not confuse bitwise & with logical &&, or Bash exponentiation ** with XOR ^.
Practice
Use parentheses to calculate (8 + 4) times 3, then compare the result with 30 using a conditional arithmetic expression. Print 36 and 1. Also predict 5 & 3 (expected 1).
Next: Validate numeric input and bases