Bash expansion order
How it works
Expansion turns source words into values and sometimes several command arguments. After parsing, Bash handles brace expansion first. Then it handles tilde, parameter, arithmetic and command substitutions from left to right, with process substitution alongside them where supported. Next come word splitting, filename expansion and removal of syntactic quotes. This is a sequence of transformations, not a second parsing of generated text. In ordinary argument positions, double-quoting a scalar expansion suppresses splitting and filename expansion of that expansion; assignments also have special rules. Quoted positional parameters and arrays have their own rules, as discussed in other lessons.
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.
Brace before variables
Expected stdout:
[noteA][noteB]Two words are generated before the prefix is substituted.
Generated text is not syntax
Expected stdout:
[{A,B}]The braces arrived too late for brace expansion.
Quoting preserves one argument
value='red blue'set -- $valueprintf '%s\n' "$#"set -- "$value"printf '%s\n' "$#"Expected stdout:
21set -- sets positional arguments; $# counts them. Quoting prevents splitting.
Common mistakes
Do not expect text obtained from a variable to become shell syntax or to trigger earlier brace expansion. Do not use eval to force it. Use literal syntax or, later, arrays for a list of arguments.
Practice
Predict both lines from printf "[%s]\n" x{1,2} and then print the value of a variable containing x{1,2} as a single argument.
Next: Brace and tilde expansion