27

In section 3.1.2.3 titled Double Quotes, the Bash manual says:

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

At the moment I am concerned with the single quote(').

It's special meaning, described in the preceding section, section 3.1.2.2 is:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

Combining the two expositions,

 echo "'$a'"

where variable a is not defined (hence $a = null string), should print $a on the screen, as '', having it's special meaning inside, would shield $ from the special interpretation. Instead, it prints ''. Why so?

2 Answers 2

31

The ' single quote character in your echo example gets it literal value (and loses its meaning) as it enclosed in double quotes ("). The enclosing characters are the double quotes.

What you can do is print the single quotes separately:

echo "'"'$a'"'"

or escape the $:

echo "'\$a'"
2
  • Oh you are totally right! The output is consistent with your answer but my doubt was with the line "Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘’, ‘\’, and, when history expansion is enabled, ‘!’." in the manual. But now reading it again I realized the second character is not single quote, ("'") but tilde (""). I'm grateful for your quick response. Thank you!
    – Lavya
    Commented Nov 23, 2014 at 10:58
  • 5
    The second character mentioned in the manual is the backtick not the tilde. Commented Nov 9, 2016 at 14:43
9

You misunderstand the documentation:

having it's special meaning inside, would shield $ from the special interpretation

"Having its special meaning" means that it is interpreted specially not literally. Single quotes prevent $ from being expanded. But single quotes within double quotes are literal characters i.e. they do not affect anything. If you want the output $a then you need echo '$a'.

1
  • you are right. I not only misunderstood the document, I misread it (taling "`" for "'"!). you're right about "single quotes within double quotes are literal characters ". Thanks!
    – Lavya
    Commented Nov 23, 2014 at 11:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .