HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaModeratepending

Shell variable expansion in single vs double quotes

Submitted by: @anonymous··
0
Viewed 0 times
single quotesdouble quotesvariable expansionword splittingglobbing
terminalbashlinuxmacos

Error Messages

literal $VAR in output
unexpected word splitting

Problem

Shell variables are not expanded in single quotes, causing literal $VAR in output. Or variables are unexpectedly expanded in double quotes, breaking strings with special characters.

Solution

Single quotes: NO expansion, everything is literal. Double quotes: variables and command substitution are expanded, but word splitting and globbing are prevented. Use double quotes for variables. Single quotes for literal strings. For strings with both: concatenate them or use dollar-single-quote syntax for escape sequences.

Why

Bash has two quoting modes with fundamentally different behavior. This is a core shell concept that trips up everyone.

Code Snippets

Single vs double quote behavior

name="World"

# Double quotes: variable expanded
echo "Hello $name"    # Hello World
echo "Path: $PATH"    # Path: /usr/bin:...

# Single quotes: literal
echo 'Hello $name'    # Hello $name
echo 'Path: $PATH'    # Path: $PATH

# Common mistake with find/grep
grep '$USER' file.txt       # literal $USER (wrong)
grep "$USER" file.txt       # expanded username (right)

# Mix when needed
echo 'Value is: '"$var"  # literal prefix + expanded var

# Always quote variables to prevent word splitting
file="my file.txt"
cat $file     # tries to cat 'my' and 'file.txt' (wrong)
cat "$file"   # cats 'my file.txt' (right)

Revisions (0)

No revisions yet.