Expansion contexts and exceptions
Expansion depends on grammar. In an ordinary argument, unquoted parameter expansion can undergo word splitting and filename expansion. A standalone scalar assignment suppresses both; assignment-like arguments to declaration builtins have special rules. Inside [[ ]], word splitting and pathname expansion are suppressed, but an unquoted right side of == is a pattern. Quoting it makes the corresponding text literal. A redirection target in normal Bash must expand to a single word; quote a filename variable to avoid an ambiguous redirect. A here string and here document have their own rules. A standalone assignment containing a command substitution returns the status of the last substitution. Combining declaration and substitution (for example local value=$(...)) may instead report the status of the declaration. Arithmetic recursively interprets some variable values as expressions; validate external numeric text and use bounded inputs. None of these contexts is an excuse to treat untrusted text as executable code. The pattern example assumes nocasematch is off. Quoting the pattern makes its characters literal but does not disable nocasematch. Check file creation before reading it.
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.
Compare expansion contexts
value='daily report'copy=$valueprintf 'assignment=[%s]\n' "$copy"printf 'argument=[%s]\n' $valueif [[ $value == 'daily report' ]]; then printf 'test=match\n'; fiExpected stdout:
assignment=[daily report]argument=[daily]argument=[report]test=matchThe assignment and conditional avoid splitting; the ordinary unquoted argument splits.
Redirect to one filename
target='daily report.txt'printf 'ready\n' > "$target" || exit 1cat -- "$target" || exit 1pattern='*.txt'[[ $target == $pattern ]] && printf 'pattern=yes\n'[[ $target == "$pattern" ]] || printf 'literal=no\n' Expected stdout:
readypattern=yesliteral=noQuoting protects the redirect and distinguishes literal comparison from a pattern.
Separate declaration and substitution
probe() { local value=$(exit 7) printf 'combined=%s\n' "$?" local other other=$(exit 7) printf 'separate=%s\n' "$?"}probeExpected stdout:
combined=0separate=7The local builtin succeeds in this fixture; the assignment reports the failed substitution.
Common mistakes
Quote filenames in redirections and literal comparison operands. Separate local declaration from command substitution when the latter status matters.
Practice
Use a value containing a space and a literal wildcard. Compare assignment, quoted argument, unquoted argument in an empty directory, and literal versus pattern tests. Explain each result.
Next: Namerefs and dynamic scoping