Shell variables should always be quoted during expansion to prevent word splitting and pathname expansion. When a variable is not quoted, the shell
treats its contents as separate words if it contains spaces, tabs, or newlines. This can cause commands to receive unexpected arguments or fail
entirely.
For example, if a variable contains a filename with spaces like my file.txt
, an unquoted expansion will be split into two separate
arguments: my
and file.txt
. This is particularly dangerous with file operations, where the wrong files might be processed or
deleted.
Pathname expansion (globbing) is another risk. If a variable contains characters like *
, ?
, or []
, the shell
will try to match them against existing files. This can lead to unintended file operations or command failures.
These issues become more severe in production environments where filenames and data are unpredictable. A script that works in testing with simple
filenames might fail catastrophically when encountering real-world data containing spaces or special characters.
What is the potential impact?
Unquoted variable expansions can cause:
- Data loss: Commands might operate on wrong files when filenames contain spaces
- Security vulnerabilities: Malicious filenames could exploit pathname expansion to access unintended files
- Script failures: Commands receiving unexpected arguments due to word splitting
- Unpredictable behavior: Scripts working in some environments but failing in others based on data content
How to fix?
Wrap variable expansions in double quotes to prevent word splitting and pathname expansion. This ensures the variable’s content is treated as a
single argument regardless of spaces or special characters.
Noncompliant code example
rm ${file} # Noncompliant
command $file1 $file2 # Noncompliant
echo $var # Noncompliant
Compliant code example
rm "${file}"
command "$file1" "$file2"
echo "$var"
Documentation
Standards