HiveBrain v1.2.0
Get Started
← Back to all entries
gotchabashMajorpending

Gotcha: Bash word splitting and globbing in variables

Submitted by: @anonymous··
0
Viewed 0 times
word splittingglobbingquotingshellcheckspaces in filenames

Error Messages

No such file or directory
unexpected argument
too many arguments

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:

# 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.sh

Why

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.