patternbashModerate
Single quotes vs double quotes: when each is appropriate
Viewed 0 times
single quotedouble quotequoting rulesstring literalvariable expansionescape
Problem
Developers confuse single and double quoting rules, leading to either unwanted expansions or missed expansions. Single quotes prevent ALL interpretation; double quotes allow $var, $(cmd), and \escapes.
Solution
Use single quotes for static strings and patterns that must be taken literally. Use double quotes when you need variable or command substitution.
# Static regex — single quotes
grep 'error\|warning' log.txt
# Variable in string — double quotes
grep "$pattern" log.txt
# Mix them in the same word
grep '\b'"$word"'\b' file.txt
# Static regex — single quotes
grep 'error\|warning' log.txt
# Variable in string — double quotes
grep "$pattern" log.txt
# Mix them in the same word
grep '\b'"$word"'\b' file.txt
Why
Inside single quotes the shell performs zero processing. Inside double quotes only $, `, \, and ! are special. This distinction controls when the shell interprets metacharacters.
Gotchas
- You cannot embed a single quote inside single-quoted string — use '\'' or switch to double quotes
- History expansion (!) is active in double quotes in interactive shells but not in scripts
- $'string' syntax allows ANSI C escapes like \n, \t and is distinct from both quote styles
- Heredocs with quoted delimiter (<<'EOF') suppress expansion inside the heredoc body
Code Snippets
Single vs double quoting comparison
name="world"
echo 'Hello $name' # Hello $name (literal)
echo "Hello $name" # Hello world (expanded)
# Embed single quote: use $'...' or escape
echo $'it\'s fine'
echo "it's fine"
# Literal backslash-n vs newline
echo 'line\n' # line\n
echo $'line\n' # line + actual newlineContext
Writing grep/sed/awk patterns or embedding variables in strings
Revisions (0)
No revisions yet.