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>
I interpret this to mean that \
should only escape one of these five special characters if it is special in its given context.
The man pages for ash, dash, bash and ksh do not contain the clause "when considered special". I take this to mean (and have confirmed through basic experimentation) that \
has the effect of escaping these five characters unconditionally, even when one of these five characters is not special in its given context.
Consider the output of $ printf '%s\n' "\abcde"
, which is \abcde
. This is expected because a
is not special in this context (or any context for that matter); therefore the \
is not special and is treated literally.
Now consider the output of $ printf '%s\n' "\\abcde"
, which is \abcde
. This is not the behavior I expect. In my mind, the first backslash in the string \\abcde
should also be treated literally, because it is followed by \
in a context where \
is not special. The output I would expect is \\abcde
.
Another scenario where I see unexpected behavior is in the output of $ printf '%s\n' "ab\$"
, which is ab$
. In my mind, $
does have a special meaning it this context because it does serve to introduce paramater expansion, commmand substitution or arithmetic expansion. Therefore, in my mind, the \
should be treated literally because it is followed by $
in a context where $
is not special. The output I would expect is ab\$
.
For the record, I hope I am totally off base here. It makes my life that much harder having to worry about escaping these five characters only in certain circumstances. I strive to be posixly correct wherever possible, and I don't want to depend on \
escaping these five special characters unconditionally if this (personally desired) behavior in mainstream POSIX-compliant shells does not fall in line with POSIX.
echo
, you are investigating how that utility is treating strings, not how the shell is interpreting escaped characters. On my systemecho "\abcd"
outputsbcd
.echo '\abcd'
outputs a BEL character (0x7 in ASCII) followed bybcd
followed by a LF character.