SC2086: Unquoted Variable Expansion in Shell Scripts
Learn why unquoted variables in bash cause word splitting and globbing bugs. Fix SC2086 by properly double-quoting variable expansions.
Detailed Explanation
Why Unquoted Variables Are Dangerous
One of the most common shell scripting mistakes is using variables without double quotes. When a variable is unquoted, the shell performs word splitting and filename globbing (pathname expansion) on its value.
The Problem
filename="my report.pdf"
rm $filename
# Shell sees: rm my report.pdf
# Deletes TWO files: "my" and "report.pdf"
With quoting:
filename="my report.pdf"
rm "$filename"
# Shell sees: rm "my report.pdf"
# Correctly deletes one file
Word Splitting
The shell splits unquoted variable values on characters in $IFS
(space, tab, newline by default). A filename with spaces becomes multiple
arguments:
path="/home/user/my documents"
cd $path # Error: /home/user/my: No such file or directory
cd "$path" # Works correctly
Globbing
Unquoted variables with glob characters (*, ?, [) are expanded
against filenames in the current directory:
pattern="*.txt"
echo $pattern # Expands to all .txt files in current directory
echo "$pattern" # Prints literal "*.txt"
When NOT to Quote
There are a few cases where you intentionally want splitting:
# Intentional word splitting for array-like behavior
flags="-v -n --color"
grep $flags pattern file # Each flag becomes a separate argument
For most cases, always double-quote your variables. Use shellcheck rule SC2086 as your guide.
Use Case
Every shell script that handles filenames, user input, or variables with potentially unexpected content needs proper quoting. This is especially critical in scripts that process files from untrusted sources, backup scripts, and deployment automation.