Why Quoting Variables Matters
Putting double quotes around a variable expansion, as in "$name", is the single most important habit in Bash scripting. Without the quotes, Bash splits the value into several words and then treats any wildcard characters in those words as patterns. With the quotes, the value reaches the command exactly as it is stored, spaces and all.
Understanding the Rule
The rule fits in one sentence: an unquoted expansion is split into words and then used as a filename pattern, and a quoted one is not. The two lessons before this one explain the mechanisms, word splitting and filename expansion. This lesson shows what they do to real commands when a variable is left unquoted.
To make the examples visible, they use a folder with a few files whose names are typical of real life:
mkdir photos && cd photos
printf 'hello\n' > "my file.txt"
printf 'plain\n' > notes.txt
printf 'x\n' > "two spaces.txt"
mkdir "my folder"
printf 'inside\n' > "my folder/inside.txt"
Two helper functions show what a command receives:
count() { echo "$# arguments"; }
show() { printf '[%s]\n' "$@"; }
What Happens to an Unquoted Expansion
When Bash meets $var outside quotes, it works in three steps:
- It replaces
$varwith its value. - It splits the value into words at spaces, tabs and newlines (word splitting).
- It treats each word that contains
*,?or[as a pattern and replaces it with matching file names (filename expansion).
With "$var" none of the last two steps happen. Everything in the following sections is a consequence of those steps.
Values With Spaces Become Several Arguments
The most common failure involves file and folder names that contain spaces:
f="my file.txt"
cat $f
cat "$f"
Output:
cat: my: No such file or directory
cat: file.txt: No such file or directory
hello
The unquoted $f became two words, my and file.txt, so cat looked for two files that do not exist. The quoted version passed one argument. The same thing happens with directories:
d="my folder"
ls $d
ls "$d"
Output:
ls: cannot access 'my': No such file or directory
ls: cannot access 'folder': No such file or directory
inside.txt
Counting arguments shows it directly:
count $f
count "$f"
count $d/inside.txt
count "$d"/inside.txt
Output:
2 arguments
1 arguments
2 arguments
1 arguments
The mistake is harmful when the command does more than read. Here mkdir creates the wrong things:
dir="new dir"
mkdir $dir
ls
Output (in a fresh, empty folder):
dir new
Instead of one folder called new dir, Bash created two folders, new and dir. A later command such as mkdir "$dir/inner" then fails with mkdir: cannot create directory 'new dir/inner': No such file or directory. With commands that remove or overwrite files, the same mistake can touch files you never meant to name, which is why a later lesson on destructive commands insists on quoting.
Empty Values Disappear
An unquoted empty variable does not become an empty argument. It becomes no argument at all, which changes the shape of the command:
target=""
count $target
count "$target"
Output:
0 arguments
1 arguments
This breaks conditions written with the [ command:
empty=""
[ $empty = "yes" ]
echo "status: $?"
[ "$empty" = "yes" ]
echo "status: $?"
Output:
bash: [: =: unary operator expected
status: 2
status: 1
After the empty variable vanished, [ saw only = yes, which is not a valid test. With quotes, [ received an empty first argument and a normal comparison was made, which was simply false (status 1).
A related trap produces a wrong answer instead of an error:
empty=""
[ -n $empty ] && echo "true"
[ -n "$empty" ] && echo "true"
Output:
true
Only the first line printed. [ -n ] with the variable gone becomes a one-argument test, which is true for any non-empty text, here the string -n. The quoted form tests the actual (empty) value and is false.
Values with spaces break the same test in the other direction:
w="a b"
[ $w = "a b" ]
echo "status: $?"
[ "$w" = "a b" ]
echo "status: $?"
Output:
bash: [: too many arguments
status: 2
status: 0
And file tests are affected in the same way:
f="my file.txt"
[ -f $f ]
echo "status: $?"
[ -f "$f" ]
echo "status: $?"
Output:
bash: [: my: binary operator expected
status: 2
status: 0
Glob Characters in Values Are Expanded
A value that contains *, ? or [ is treated as a pattern when it is unquoted, even if you meant plain text:
note="Total: 5 * 3"
echo $note
echo "$note"
Output (in the photos folder):
Total: 5 my file.txt my folder notes.txt two spaces.txt 3
Total: 5 * 3
The * matched every name in the folder. The effect is harmless with echo, but a program such as rm would treat the names as targets.
Patterns passed to commands that do their own matching are affected too:
pattern="*.txt"
find . -maxdepth 1 -name $pattern
find . -maxdepth 1 -name "$pattern"
Output (find does not sort its results, so the order of the three names may differ on your system):
find: paths must precede expression: `notes.txt'
find: possible unquoted pattern after predicate `-name'?
./my file.txt
./notes.txt
./two spaces.txt
The unquoted $pattern was expanded by the shell into three file names, so find received -name "my file.txt" notes.txt "two spaces.txt" and rejected the extra words. The quoted form delivered the literal *.txt for find to use.
Whitespace and Newlines Are Lost
Splitting also discards the exact spacing of a value, because the words are rejoined with single spaces by echo:
text=$'line one\n line two\twith tab'
echo $text
echo "$text"
Output:
line one line two with tab
line one
line two with tab
The quoted version preserved the newline, the leading spaces and the tab. This matters whenever you print, log or pass multi-line text.
Values That Start With a Dash
A value that begins with - can be mistaken for an option. Quotes do not solve this by themselves, because the shell removes them before the command runs, but they combine with the -- marker or a ./ prefix:
This example uses its own empty folder, so the odd file name does not affect the other examples:
mkdir dashdemo && cd dashdemo
touch -- "-v.txt"
name="-v.txt"
ls $name
ls -- "$name"
ls ./"$name"
cd ..
Output:
ls: invalid option -- '.'
Try 'ls --help' for more information.
-v.txt
./-v.txt
ls read -v.txt as a group of options. The first one, -v, is valid, but the . that follows is not, so it stopped with an error. The -- tells ls that options have ended, and ./ makes the name start with something other than a dash. The quotes in both working forms still protect against spaces.
Command Substitution and Loops
The output of $(...) is split like any other value. A loop over $(ls) breaks on names with spaces, because it loops over words instead of names:
for f in $(ls *.txt); do echo "piece: $f"; done
Output:
piece: my
piece: file.txt
piece: notes.txt
piece: two
piece: spaces.txt
Looping over a pattern is safe, because filename expansion produces one word per file:
for f in *.txt; do echo "item: $f"; done
Output:
item: my file.txt
item: notes.txt
item: two spaces.txt
Reading a list of lines is also safer with while read than with for:
printf 'my file.txt\nnotes.txt\n' > list.txt
while IFS= read -r line; do echo "line: $line"; done < list.txt
for line in $(cat list.txt); do echo "word: $line"; done
Output:
line: my file.txt
line: notes.txt
word: my
word: file.txt
word: notes.txt
Arrays and Positional Parameters
Arrays follow the same rule, and the special form "${array[@]}" is how you pass every element as its own word:
files=("my file.txt" "notes.txt")
count ${files[@]}
count "${files[@]}"
count "${files[*]}"
Output:
3 arguments
2 arguments
1 arguments
- Unquoted
${files[@]}was split again, somy file.txtbecame two words. "${files[@]}"kept one word per element."${files[*]}"joined everything into a single word.
The script arguments $@ behave the same way:
args() { count $@; count "$@"; }
args "a b" "c d"
Output:
4 arguments
2 arguments
Quoting Inside Command Substitution
Quotes inside $(...) are independent of the quotes outside. Writing both pairs is correct and is the usual form:
f="my notes.txt"
printf 'hello\n' > "$f"
echo "$(basename "$f")"
echo "$(basename $f)"
Output:
my notes.txt
my
In the second command the inner $f was not quoted, so basename received two arguments, my and notes.txt. It treats a second argument as a suffix to remove, and it printed my. The outer quotes alone are not enough; each expansion needs its own.
Places Where Quotes Are Optional
Quotes are not required in contexts where Bash does no splitting or globbing:
a="x y"
b=$a
echo "$b"
case $a in "x y") echo "case ok";; esac
[[ $a == "x y" ]] && echo "[[ ok"
Output:
x y
case ok
[[ ok
- A plain assignment such as
b=$astores the value without splitting. - The word after
caseis not split. - Inside
[[ ... ]]the left side is not split.
Adding quotes in these places does no harm. The one place where quotes change the meaning inside [[ ]] is the right side of ==, which is treated as a pattern unless it is quoted:
pat="a*"
[[ "a b" == $pat ]] && echo "unquoted: pattern, match"
[[ "a b" == "$pat" ]] || echo "quoted: literal, no match"
Output:
unquoted: pattern, match
quoted: literal, no match
A Simple Rule in Practice
Quote every $ expansion, including "$var", "${var}", "$(command)", "$@" and "${array[@]}", and leave the quotes off only when you specifically want splitting or globbing. That choice is rare, and it should be visible in the code, for example with a comment. The static checker ShellCheck, covered in a later lesson, reports unquoted expansions with its warning SC2086, "Double quote to prevent globbing and word splitting". Scripts that also use set -u, described in a later lesson, catch variables that were never set, which complements quoting.