Shell – POSIX Shell: inside of double-quotes, are there cases where `\` fails to escape `$`, “`, `”`, `\` or ``

posixquotingshell

Per the POSIX Shell Command Language Page:

\

The <backslash> shall retain its special meaning as an escape character (see Escape Character (Backslash)) only when followed by one of the following characters when considered special:

$ ` " \ <newline>

This would seem to imply that escaping these five characters with a backslash would not have the effect of escaping them and having them be treated literally if they are not "special".

Am I interpreting this correctly, and if so, are there cases where escaping one of these five special characters with a \ would not have the intended effect of escaping it?

Best Answer

@MichaelHomer explains it very well. Let's try a few practical cases with PS1='\$ ':

$ echo "$ at start"
$ at start
$ echo "at end $"
at end $
$ echo "$before"

$ echo "after$"
after$

So $ is only "special" before a word, making it a parameter substitution. What happens if we put a backslash before all of them?

$ echo "\$ at start"
$ at start
$ echo "at end \$"
at end $
$ echo "\$before"
$before
$ echo "after\$"
after$

Only the "special" line changes - the dollar sign is now considered literal. It was always considered literal. What happens with other characters?

$ echo "\ at start"
\ at start
$ echo "at end \"
> ^C
$ echo "\before"
\before
$ echo "after\"
> ^C

So backslash is just another literal character before a non-special character. (^C is where I had to cancel the command line because the quote character had been escaped.)

Related Question