I’m trying to terminate a line with \ and have something else on a new line.
At first I did this but it just prints the \n:
$ echo -e "Test\\\nNewline"
Test\nNewlineI tried this way but it add a space following the backslash:
$ echo -e "Test\\ \nNewline"
Test\
NewlineHow can I do this so there is no space after the \?
UPDATE: There isn't a problem now as I see that adding two more slash gets the result I want. But I am still wondering why it does?
$ echo -e "Test\\\\\nNewline"
Test\
Newline 2 2 Answers
Bash Reference Manual: Double Quotes: Within double quotes, backslashes that are followed by one of these characters [including backslash] are removed.
Therefore, "Test\\\\\nNewline" is replaced with Test\\nNewline before being passed as a parameter to the echo command.
To demonstrate this:
$ echo -e "Test\\\\\nNewline"
Test\
Newline
$ echo -e 'Test\\\nNewline'
Test\
Newline 10 Steven's already explained why so many backslashes are necessary; I'd like to list some possibly-better ways to do the same thing. First, using single-quotes instead of double-quotes skips the extra level of escape interpretation/removal:
$ echo -e "Test\\\nNewline"
Test\nNewline
$ echo -e 'Test\\\nNewline'
Test\
NewlineSecond, I recommend against using echo for things like this, since different versions of it behave quite differently: some will interpret escape sequences in the string (like \n) even without the -e option, some will print the "-e" as part of their output, etc. Here's an example using /bin/echo instead of the bash builtin version:
$ /bin/echo -e 'Test\\\nNewline'
-e Test\\\nNewline...That's on OS X v10.10.4; it may be different on your OS and/or version. Anytime you want predictable behavior with escape interpretation and/or leaving off the final linefeed, I recommend printf instead of echo. It's a little more complicated: the first argument to printf is a format string, in which escapes are always interpreted, and that can also include % sequences that'll be used to add in the remaining arguments (in which escape sequences are not interpreted). Also, printf doesn't automatically add a linefeed at the end, you have to include that explicitly. Here are a couple of ways to print what you want with printf:
$ printf 'Test\\\nNewline\n' # note explicit final newline
Test\
Newline
$ printf '%s\n' 'Test\' 'Newline' # Escape is interpreted in the format string, but not in the second argument
Test\
Newline 5