0

according to gnu doc,

The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘"’, ‘\’, or newline. Within double quotes, backslashes that are followed by one of these characters are removed.

I tried

p="a\$b";echo $p  # a$b
p="a\`b";echo $p  # a`b
p="a\"b";echo $p  # a"b
p="a\\b";echo $p  # a\b

all is ok. But newline??

p="a\newlineb";echo $p  # a\newlineb

What does newline mean in the doc?

4

Newline is the name of the newline character, i.e. the character usually written as \n in C:

$ p="a\
b"; echo "$p"
ab

The result is ab rather than \a<newline>b since the POSIX standard says:

A <backslash> that is not quoted shall preserve the literal value of the following character, with the exception of a <newline>. If a <newline> follows the <backslash> the shell shall interpret this as line continuation. The <backslash> and <newline> shall be removed before splitting the input into tokens. Since the escaped <newline> is removed entirely from the input and is not replaced by any white space, it cannot serve as a token separator.

But the string is quoted with double quotes... Well, this is a special case:

The <backslash> shall retain its special meaning as an escape character only when followed by one of the following characters when considered special: $, `, ", \, <newline>.

So the double-quoted string means that the backslash-newline is interpreted as if it was not quoted at all, which means it act as a line-continuation and both the backslash and newline are removed.

Note that this happens as you assign to the p variable, not when you echo it.

See also "http://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells" about the neccecity of quoting your variables, always.

  • Is the output being shown ab ? Where has the newline vanished when the variable was quoted ? – user218374 Apr 17 '17 at 23:18
  • @RakeshSharma Please read updated answer. – sorontar Apr 19 '17 at 2:22
  • Maybe also highlight the necessity of quoting the echo argument, though it doesn't particularly make a difference in this specific case. – tripleee Apr 19 '17 at 6:10
  • @sorontar Thanks for the edit, but I've replaced it with a POSIX ref instead. :-) – Kusalananda Apr 19 '17 at 6:25
  • @Kusalananda That is perfectly correct and valid (also for bash), so no complaints, instead: Many thanks :). – sorontar Apr 19 '17 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.