gotchabashMajorpending
Gotcha: Bash word splitting and globbing in variables
Viewed 0 times
word splittingglobbingquotingshellcheckspaces in filenames
Error Messages
Problem
Unquoted variables in bash cause unexpected word splitting and filename globbing, breaking scripts with spaces or special characters.
Solution
Always quote variables in bash:
Shellcheck catches these:
# BAD: Word splitting
FILE="my document.txt"
cp $FILE /dest/ # Runs: cp my document.txt /dest/
# (3 arguments instead of 2!)
# GOOD: Quoted
cp "$FILE" /dest/ # Runs: cp 'my document.txt' /dest/
# BAD: Globbing
PATTERN="*.txt"
echo $PATTERN # Expands to matching files!
# GOOD: Quoted
echo "$PATTERN" # Prints: *.txt
# BAD: Array iteration
FILES=("file 1.txt" "file 2.txt")
for f in $FILES; do # Only processes "file"!
for f in ${FILES[@]}; do # Word splits on spaces!
# GOOD: Quoted array
for f in "${FILES[@]}"; do
echo "$f" # Correct: 'file 1.txt', 'file 2.txt'
done
# When you WANT splitting (rare):
read -ra ARGS <<< "$INPUT" # Split into array explicitly
# Rule: Always use "$var" unless you have a specific
# reason not to and understand the implications.Shellcheck catches these:
shellcheck myscript.shWhy
Bash performs word splitting and pathname expansion on unquoted variables. This is the #1 source of shell script bugs.
Context
Any bash script that handles filenames or user input
Revisions (0)
No revisions yet.