Parser, tokens and grammar contexts
Bash first recognizes syntax from source text, then expands eligible words. A token can be a word or an operator; a reserved word has special meaning only in an eligible grammatical position when unquoted. For example, if at the start of a conditional is syntax, but printf '%s\n' if passes it as ordinary data. A variable containing a semicolon does not create a command separator when expanded. Unquoted expansion may split words or match filenames, but does not normally reparse the result as shell grammar. Avoid explicit reparsing of data with eval. Aliases are expanded while Bash reads commands, not when it later runs them. An alias defined inside an already-read compound command is not available to later words in that same parsed command. Functions are parsed at definition time; enabling syntax-changing options such as extglob must happen before the relevant syntax is read (outside the function definition). Use functions for runtime argument handling rather than aliases. These are language-level rules, not a claim about exact parser implementation steps.
Conceptual reading order: source tokens → grammar and alias processing → contextual word expansion → execution. For the extglob example, use bash -O extglob -n script.sh for syntax checking: plain bash -n does not execute the preceding shopt command. Use a separate script for the alias example; reading the entire sequence as one compound command changes alias availability. For the extended-pattern syntax check, enable extglob at Bash invocation, not merely inside the script.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Syntax versus data
if true; then printf '%s\n' if; fitext='one; two'printf '[%s]\n' "$text"Expected stdout:
if[one; two]The first if is grammar; the second is an argument. The expanded semicolon stays data.
Alias read timing
shopt -s expand_aliasesalias bmword='printf "old\\n"'show() { bmword; }alias bmword='printf "new\\n"'showbmwordExpected stdout:
oldnewThe function retains the expansion read at definition time. The later standalone command uses the new alias.
Enable grammar before a definition
shopt -s extglobcheck() { case $1 in +(ab)) printf 'match\n';; *) printf 'other\n';; esac}check ababcheck abcExpected stdout:
matchotherThe extended pattern means one or more copies of ab. Its parentheses must be parsed in the correct context.
Common mistakes
Do not confuse text containing syntax with actual source syntax. Enable extglob before reading a function using extended glob patterns.
Practice
Predict the arguments passed by a quoted variable containing ;, then compare a reserved word in a conditional with the same word passed to printf. Explain why the two contexts differ.
Next: Expansion contexts and exceptions