The Expansion Order: A Critical Sequence

Updated

October 31, 2026

The Expansion Order: A Critical Sequence

The most common source of elusive Bash bugs is misunderstanding the Expansion Order. Bash evaluates expansions strictly in this sequence:

  1. Brace Expansion: {a,b,c} and {1..5}
  2. Tilde Expansion: ~ and ~user
  3. Parameter & Variable Expansion: $VAR and ${VAR:-default}
  4. Arithmetic Expansion: $(( 2 + 2 ))
  5. Command Substitution: $(command)
  6. Process Substitution: <(command) and >(command)
  7. Word Splitting: Splits results of unquoted expansions on $IFS characters
  8. Pathname Expansion (Globbing): *.txt, [a-z]*
  9. Quote Removal: Strips unquoted single quotes, double quotes, and backslashes

Why Order Matters: The Variable in Brace Pitfall

# This DOES NOT WORK because Brace Expansion happens BEFORE Parameter Expansion:
count=5
echo {1..$count}
# Output: {1..5} (literal text, not 1 2 3 4 5!)

# Solution: Use standard C-style loops or seq:
for ((i=1; i<=count; i++)); do
    echo "$i"
done