Question

I'm looking at some linux specific code which is outputting the likes of:

\r\x1b[J>

to the std io.

I understand that <ESC>[J represents deleting the contents of the screen from the current line down, but what does \r do here?

I'm also seeing the following:

>user_input\n\r>

where user_input is the text entered by the user. But what is the purpose of the \r here?

Was it helpful?

Solution

The character '\r' is carriage return. It returns the cursor to the start of the line.

It is often used in Internet protocols conjunction with newline ('\n') to mark the end of a line (most standards specifies it as "\r\n", but some allows the wrong way around). On Windows the carriage-return newline pair is also used as end-of-line. On the old Macintosh operating system (before OSX) a single carriage-return was used instead of newline as end-of-line, while UNIX and UNIX-like systems (like Linux and OSX) uses a single newline.

OTHER TIPS

Control character \r moves caret (a.k.a text cursor) to the leftmost position within current line.

From Wikipedia

Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A). These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer thus instructed the printer to advance the paper one line, and a carriage return indicated that the printer carriage should return to the beginning of the current line. Some rare systems, such as QNX before version 4, used the ASCII RS (record separator, 0x1E, 30 in decimal) character as the newline character.

FWIW - this is a part of carriage control - from mainframe control words to Windows/UNIX/FORTRAN carriage control. Carriage control can be implemented at a language level like FORTRAN does, or system-wide like UNIX and Windows do.

\n arose from limitations of early PDP user "interfaces" - the tty terminal. Go to a museum if you want see one.

A very simple point: The difference between \n \r is explained above. But all of these explanations are really saying that carriage control is implementation dependent.

The [J is part of ANSI escape sequences and what they do on a "standards conforming tty terminal". DOS used to have ANSI.SYS to provide: colors, underline, bold using those sequences.

http://ascii-table.com/ansi-escape-sequences.php

Is a good reference for the question: what does some odd looking string in the output do?

\r is carriage return. Similarly \n is linefeed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top