Bash Quoting
Quoting decides what Bash does with special characters such as spaces, $, * and \. Most shell bugs, from "my script breaks on file names with spaces" to accidental deletions, come down to quoting. The rules are short; learn them well.
Three kinds of quoting
| Quoting | Example | What happens |
|---|---|---|
| Single quotes | '$HOME *' |
Everything literal: no expansion at all |
| Double quotes | "$HOME *" |
Variables, $( ) and $(( )) expand; spaces and * are kept literally |
| Backslash | \$HOME |
Escapes the single next character |
item="coffee beans"
echo 'Single: $item $(echo hi) *'
echo "Double: $item $(echo hi) *"
echo Backslash: \$item \*
echo "Inside double quotes: \"quoted\" and \$item"Single: $item $(echo hi) *
Double: coffee beans hi *
Backslash: $item *
Inside double quotes: "quoted" and $item
Word splitting: why "$var" matters
When a variable is used without double quotes, Bash splits its value on spaces into separate words and expands wildcards in it. Inside double quotes the value stays one word:
file="annual report.txt"
touch "$file"
ls $file
echo "--- with quotes:"
ls "$file"ls: cannot access 'annual': No such file or directory
ls: cannot access 'report.txt': No such file or directory
--- with quotes:
annual report.txt
Unquoted, ls got two arguments: annual and report.txt. With quotes it got one. A small helper shows exactly how many arguments a command receives:
count_args() { echo "$# args:$(printf ' [%s]' "$@")"; }
title="The Linux Command Line"
count_args $title
count_args "$title"
count_args '$title'4 args: [The] [Linux] [Command] [Line]
1 args: [The Linux Command Line]
1 args: [$title]
Note how the unquoted version also lost the extra spaces.
Rule of thumb: Always put variable and command-substitution expansions in double quotes,
"$var"and"$(cmd)", unless you specifically want splitting. Tools like ShellCheck warn about every unquoted expansion.
Wildcards inside variables
Unquoted expansions also go through globbing:
touch a.txt b.txt
pattern="*.txt"
echo $pattern
echo "$pattern"a.txt b.txt
*.txt
"$@": passing arguments on safely
"$@" expands to all arguments, each as its own word, exactly as received. $* and unquoted $@ re-split them:
show() { for arg in "$@"; do echo " <$arg>"; done; }
forward_good() { show "$@"; }
forward_bad() { show $@; }
echo "good:"; forward_good "New York" "Rio de Janeiro"
echo "bad:"; forward_bad "New York" "Rio de Janeiro"good:
<New York>
<Rio de Janeiro>
bad:
<New>
<York>
<Rio>
<de>
<Janeiro>
Always write "$@" when passing arguments to another command.
Quotes inside quotes
| You want | Write |
|---|---|
| A double quote in double quotes | "say \"hi\"" |
| A single quote in single quotes | 'it'\''s' (end, escaped quote, restart) |
| A single quote, easier | "it's" |
Escapes like \n and \t |
#39;line1\nline2' (ANSI-C quoting) |
echo "She said \"hello\""
echo 'It'\''s fine'
echo "It's also fine"
echo