简体   繁体   中英

End of line (new line) escapes in bash

Escape character ( \\ ) can be used to escape end of line, eg

% echo This could be \
a very \
long line\!
This could be a very long line!
%

however, isn't end of line (new line) represented by \\n which has two characters. shouldn't the result of the escape be the literal of \\n . eg

%echo $'\\n'
\n
%

Thank you for your answer!

Edit: Sorry, I didn't explain it well enough. I am not trying to echo a new line. I am wondering why \\ is able to new line character ( \\n ) which has two character instead of just escape the backslash in the new line character and produce the literal of \\n

Actually, \\n is not really a newline character -- it is an escape sequence that represents a newline (which is just one character in Linux). The \\ at the end of a line escapes the actual newline character that you type in using the enter key. You can look at what ASCII values represent different characters using hexdump :

%echo $'\\n'
\n
%echo $'\\n' | hexdump -C
00000000  5c 6e 0a                   |\n.|
00000003

You will notice that echo printed out 3 characters: \\ (5c), n (6e), and a newline (0a). You will also notice that on the right hand side of the hexdump output, newline shows up as a ".", because it is considered a non-printing character .

Newline is the name given in the UNIX world to a character that ends a line in a line-oriented file (or in a terminal). In the UNIX/Linux world this corresponds to the ASCII linefeed character.

Different systems use different conventions to end lines: Windows uses a sequence of carriage return and line feed, while Mac originally used a single carriage return. This confusion stems from the fact that these were originally commands needed to move a printer's print head to the beginning of a new line.

\\n is a conventional way of expressing the end of line character in code, again originally in the UNIX world, more precisely in the C language. Note that when reading a text file C reads a single newline character even on systems where this is really a two character sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM