2
While working in a (Unix) shell, sometimes I need to double-quote single-quotes or vice versa, i.e. to write something like "foo 'bar baz' moo"
or 'foo "bar baz" moo'
. This may be because
- the resulting string will be parsed again (like with
eval
, with a shell run bywatch
, with a shell run bysshd
on some remote server etc.) and these inner quotes are crucial to distinguish actual arguments during this second parsing; - or I just need the original argument to include quotes for whatever other reason.
Some ambiguity appears when instead of bar baz
I have a variable, say $variable
. This is what POSIX says:
2.2.2 Single-Quotes
Enclosing characters in single-quotes (
''
) shall preserve the literal value of each character within the single-quotes. A single-quote cannot occur within single-quotes.2.2.3 Double-Quotes
Enclosing characters in double-quotes (
""
) shall preserve the literal value of all characters within the double-quotes, with the exception of the characters backquote, <dollar-sign>, and <backslash>, as follows:
$
The shall retain its special meaning introducing parameter expansion […], a form of command substitution […], and arithmetic expansion […].[…]
It's not exactly obvious which rule applies for $variable
inside single-quotes inside double-quotes (or inside double-quotes inside single-quotes), therefore I'm asking:
Which rule applies to:
-
variable=123 echo "'$variable'"
-
variable=123 echo '"$variable"'
(I'm aware this can be easily answered just by trying, it would be a reasonable research effort. I decided to put this effort into the community wiki answer below).
-
Are there any exceptions, quirks, surprises?
(Please note there is a community wiki answer below. Instead of adding a separate answer with another exception or quirk, consider contributing to the community wiki one).