gotchabashCritical
Always quote variables to prevent word splitting and glob expansion
Viewed 0 times
quotingword splittingglob expansionIFSdouble quotevariable expansion
Problem
Unquoted variables undergo word splitting and glob expansion. A variable containing spaces or glob characters will be broken into multiple arguments or expanded to matching filenames unexpectedly. Example: FILE='my file.txt'; rm $FILE tries to remove 'my' and 'file.txt' separately.
Solution
Always double-quote variable expansions: rm "$FILE". Use single quotes for literal strings where no expansion is wanted. Use double quotes when you need variable or command substitution but want to suppress word splitting.
# BAD
for f in $FILES; do ...
# GOOD
for f in "$FILES"; do ... # if single path
# Or use an array:
files=("file one.txt" "file two.txt")
for f in "${files[@]}"; do ...
# BAD
for f in $FILES; do ...
# GOOD
for f in "$FILES"; do ... # if single path
# Or use an array:
files=("file one.txt" "file two.txt")
for f in "${files[@]}"; do ...
Why
The shell splits unquoted expansions on characters in $IFS (space, tab, newline by default), then applies glob expansion to each resulting word. Quoting suppresses both steps.
Gotchas
- "$@" preserves individual argument boundaries; $@ without quotes collapses them
- "$*" joins all arguments into one string with IFS[0] as separator
- Arrays require "${arr[@]}" not "${arr[*]}" to preserve element boundaries
- Quoting inside [[ ]] is optional for the right-hand side of = but still good practice
Code Snippets
Word splitting and glob expansion example
# BAD — word splitting breaks the filename
file="my report.pdf"
rm $file # tries to rm 'my' and 'report.pdf'
# GOOD
rm "$file" # treats as single argument
# BAD — glob expansion surprises
pattern="*.log"
ls $pattern # expands *.log in current dir
# GOOD — explicit glob when you want expansion, quoted when you don't
ls "$pattern" # passes literal *.log to lsContext
Any script that handles filenames, user input, or paths containing spaces
Revisions (0)
No revisions yet.