The Expansion Order: A Critical Sequence
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:
- Brace Expansion:
{a,b,c}and{1..5} - Tilde Expansion:
~and~user - Parameter & Variable Expansion:
$VARand${VAR:-default} - Arithmetic Expansion:
$(( 2 + 2 )) - Command Substitution:
$(command) - Process Substitution:
<(command)and>(command) - Word Splitting: Splits results of unquoted expansions on
$IFScharacters - Pathname Expansion (Globbing):
*.txt,[a-z]* - 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