Shell Script by Example: Quoting Rules
Understanding shell quoting mechanisms with this code example covering double quotes for variable expansion, single quotes for literal strings, escaping special characters with backslash, and proper quoting to handle filenames containing spaces.
Code
#!/bin/bash
name="Alice"
# Double quotes: Variable expansion happens
echo "Double: Hello, $name"
# Output: Double: Hello, Alice
# Single quotes: Literal string (no expansion)
echo 'Single: Hello, $name'
# Output: Single: Hello, $name
# Escaping characters
echo "Cost: \$100"
# Quoting to handle spaces
filename="My Document.txt"
# rm $filename # ERROR: tries to remove "My" and "Document.txt"
# rm "$filename" # CORRECT: removes "My Document.txt"Explanation
Quoting is one of the most critical and confusing aspects of shell scripting, controlling how the shell interprets special characters. Double quotes "..." allow variable expansion and command substitution, meaning $variable inside double quotes is replaced by its value. Special characters like $, backticks, and backslashes retain their special meaning within double quotes unless escaped with a backslash.
Single quotes '...' preserve the literal value of every character within them. No expansion or interpretation occurs inside single quotes, making them ideal when you need to print exactly what you type, including dollar signs, backslashes, or other special characters. You cannot include a single quote within single quotes, even with escaping; you must end the quoted string, add an escaped quote, and start a new quoted string.
Quoting is essential when dealing with filenames or strings containing spaces. Without quotes, the shell performs word splitting, breaking a single filename with spaces into multiple arguments. This leads to errors like attempting to delete multiple files instead of one. Always quote your variables using "$var" to prevent word splitting and globbing issues. This practice is especially important in production scripts where filenames are unpredictable.
Code Breakdown
"..." allows $name to expand to "Alice" within the string.'...' treats $name as literal text characters, no expansion.\$ escapes the dollar sign to print it literally as "$100"."$filename" prevents word splitting on the space in the filename.
