December 5, 2026

Single vs Double Quotes in Bash: Tested Examples, From $name to “$@”

A laptop terminal window on a desk at night

Running ls $f on a file called “my file.txt” produces two errors: Bash looked for a file named my and another named file.txt, and found neither. Adding two double quotes, ls "$f", fixes it. That one habit, quoting variables, prevents most of the strange failures shell scripts hit when file names contain spaces, and it is the first warning the ShellCheck linter gives. The rules behind it are short. Single quotes freeze everything. Double quotes freeze everything except a handful of characters. Every example below was run in GNU Bash 5.2, and the output shown is what Bash printed.

Video: anthonywritescode on YouTube

The two rules

Single quotes

The Bash Reference Manual’s section on single quotes is two sentences long: enclosing characters in single quotes preserves the literal value of each one, and a single quote may not occur between single quotes, even when preceded by a backslash. Nothing inside expands. Not variables, not backslashes, not anything.

Double quotes

The manual’s section on double quotes says they preserve the literal value of all characters inside, with the exception of $, the backtick, the backslash, and ! when history expansion is turned on. A backslash keeps its special meaning only before $, a backtick, ", \ or a newline.

The first test

name="World"
echo 'Hello $name'     # Hello $name
echo "Hello $name"     # Hello World
White and red cutout letters

Escaping inside double quotes

The five characters a backslash still escapes

echo "Cost: \$5 and a \"quote\" and a backtick \` and \\"
# Cost: $5 and a "quote" and a backtick ` and \

Every backslash in that line sits before one of the characters the manual lists, so each one is removed and the next character comes through literally.

Nesting command substitution

Inside $( ), quoting starts fresh, so double quotes can nest without escaping:

echo "$(echo "nested \"quotes\" work")"
# nested "quotes" work

A variable holding a double quote

x='a"b'; echo "$x"    # a"b

Quotes that come from a variable’s value are just data. Bash doesn’t re-read them as syntax.

Getting a single quote into single quotes

The close-escape-reopen trick

Because a single quote can’t appear inside single quotes, the standard workaround closes the quote, adds an escaped single quote outside any quotes, and reopens:

echo 'It'\''s fine'     # It's fine

Bash sees three pieces glued together: 'It', \', and 's fine'.

ANSI-C quoting

Bash also has a third form. The manual’s ANSI-C quoting section says character sequences of the form $'string' are treated as a special kind of single quotes, where backslash escapes such as \t, \n and \' are decoded:

echo $'tab:\there\nnewline'
# tab:  here
# newline

Let Bash do the quoting

printf '%q' prints a value in a form the shell can read back safely:

printf '%q\n' "it's a \$test"
# it\'s\ a\ \$test
A black piece of paper with a white background

Why unquoted variables break

Word splitting

f="my file.txt"; touch "$f"
ls $f
# ls: cannot access 'my': No such file or directory
# ls: cannot access 'file.txt': No such file or directory
ls "$f"
# my file.txt

An unquoted variable’s value is split on spaces, tabs and newlines into separate words. ShellCheck’s warning SC2086 is titled “Double quote to prevent globbing and word splitting,” and its explanation says quoting prevents the script from breaking when input contains spaces, line feeds or glob characters.

Whitespace collapses

v="  spaced   out  "
echo [$v]       # [ spaced out ]
echo ["$v"]     # [  spaced   out  ]

Unquoted, the leading, trailing and doubled spaces vanish, because they became word separators and echo joins its arguments with single spaces.

Globbing

star="*"
echo $star | wc -w      # 3
echo "$star"            # *

Unquoted, the * expanded to every file in the test directory: my file.txt and t.sh, which wc -w counted as three words. Quoted, it stayed a literal asterisk. A variable that happens to contain * or ? can silently turn into a list of file names.

The empty-string test

empty=""
[ -n $empty ]   && echo "unquoted -n says non-empty"
[ -n "$empty" ] || echo "quoted -n says empty"
# unquoted -n says non-empty
# quoted -n says empty

Unquoted, the empty variable disappears entirely, leaving [ -n ]. A test with a single argument is true if that argument is non-empty, and -n is non-empty. The check reports the opposite of the truth.

“$@” versus $@ versus “$*”

The test

set -- "a b" c
for x in $@;   do echo "[$x]"; done   # [a] [b] [c]
for x in "$@"; do echo "[$x]"; done   # [a b] [c]
echo "[$*]"                           # [a b c]

What each form does

The double-quotes section of the manual notes that $@ and $* have special meaning inside double quotes. Quoted "$@" expands to each original argument as its own word, spaces intact, which is almost always what a script wants when passing arguments along. Unquoted $@ re-splits everything, so the argument “a b” breaks in two. Quoted "$*" joins all arguments into one string separated by the first character of IFS, a space by default.

The rule of thumb

Use "$@" to forward arguments. Use "$*" only to build a single message string. Never use either unquoted.

Envelope paper lot

Heredocs, arrays and nested shells

Quoting the heredoc delimiter

A heredoc behaves like double quotes unless its delimiter is quoted, in which case it behaves like single quotes:

cat <<EOF
Unquoted heredoc: $name $(echo cmd)
EOF
# Unquoted heredoc: World cmd

cat <<'EOF'
Quoted heredoc: $name $(echo cmd)
EOF
# Quoted heredoc: $name $(echo cmd)

Writing a script or a config file that itself contains $ signs, such as a shell script generated by another script, calls for the quoted form. Otherwise every variable in the generated text gets filled in at generation time, usually with an empty string.

Arrays need the same care

arr=("one two" three)
printf '[%s]\n' ${arr[@]}      # [one] [two] [three]
printf '[%s]\n' "${arr[@]}"    # [one two] [three]

An array is the right way to hold a list of file names or arguments that may contain spaces, but only when it’s expanded as "${arr[@]}". Without the quotes, the array’s careful boundaries are thrown away and the elements are split again, exactly like $@.

Passing values into a nested shell

Commands such as find -exec sh -c, ssh and bash -c start a second shell that parses its command string all over again. The safe pattern is to keep the command string in single quotes and pass values in as positional arguments:

find . -name '*.txt' -exec sh -c 'echo "got: $1"' _ {} \;
# got: ./a b.txt
# got: ./c.txt

The underscore fills $0, and each file name arrives in $1 intact, spaces included. The tempting alternative of building the command in double quotes, such as bash -c "echo inner sees: \$name", printed inner sees: with nothing after it in the test, because the escaped $name was expanded by the inner shell, where an unexported variable doesn’t exist. Passing the value as an argument, bash -c 'echo "inner sees: $0"' "$name2" with name2="x y", printed inner sees: x y.

A short reference

When to use which

Situation Use Example
Literal text, no expansion wanted single quotes grep 'a$b' file
Text with variables double quotes echo "Hello $name"
Any variable as a command argument double quotes rm -- "$f"
Forwarding all arguments "$@" exec "$cmd" "$@"
Escapes like tab or newline $'...' IFS=$'\n'
Building a command for later printf '%q' printf '%q ' "$@"

Tooling that catches mistakes

ShellCheck flags unquoted variables, along with many other common shell bugs, and runs in most editors and in CI pipelines. Running it on an existing script is usually the fastest way to find the quoting problems already there.

Catching the empty variable early

Quoting stops an empty or unset variable from vanishing, but it doesn’t flag that the variable was empty in the first place. Two Bash options help. A default inside the expansion, "${nope:-fallback}", printed fallback in the test when nope was unset. And set -u at the top of a script turns any use of an unset variable into an error: with it enabled, echo "$nope" stopped the script with the message nope: unbound variable instead of quietly printing an empty line. Combined with quoting everywhere, that catches the typo in a variable name that would otherwise pass an empty string to a command like rm.

A reference shelf

As an Amazon Associate I earn from qualifying purchases. A commission may be earned if you buy through this link, at no extra cost to you.

Sources

  • Bash Reference Manual, “Single Quotes” (mirror hosted by Princeton Plasma Physics Laboratory): https://w3.pppl.gov/info/bash/Single_Quotes.html
  • GNU Bash Reference Manual, “Double Quotes”: https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
  • GNU Bash Reference Manual, “ANSI-C Quoting”: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
  • ShellCheck wiki, SC2086: https://www.shellcheck.net/wiki/SC2086

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *