How does clear command work?

The output of the clear command is console escape codes. The exact codes required depend on the exact terminal you are using, however most use ANSI control sequences. Here is a good link explaining the various codes - http://www.termsys.demon.co.uk/vtansi.htm. The relevant snippets are:

Cursor Home         <ESC>[{ROW};{COLUMN}H

Sets the cursor position where subsequent text will begin. If no row/column
parameters are provided (ie. <ESC>[H), the cursor will move to the home position,
at the upper left of the screen.

And:

Erase Screen        <ESC>[2J

Erases the screen with the background colour and moves the cursor to home.

Where <ESC> is hex 1B or octal 033. Another way to view the characters is with:

clear | sed -n l

It works by issuing certain ANSI escape sequences. Specifically, these two:

Esc[Line;ColumnH          Cursor Position:
Esc[Line;Columnf            Moves the cursor to the specified position (coordinates). If you do not
                                         specify a position, the cursor moves to the home position at the upper-left
                                         corner of the screen (line 0, column 0).

Esc[2J                              Erase Display:
                                         Clears the screen and moves the cursor to the home position
                                         (line 0, column 0).

This is perhaps easier to understand in the output of od -c:

$ clear | od -c
0000000 033   [   H 033   [   2   J
0000007

033 is Esc, so the output above is simply Esc[H and then Esc[2J.


The output sent by clear(1) depends on your terminal type, defined by $TERM in the shell environment. It does the same thing as the command "tput clear", which is looking up the escape code for the current terminal type and sending that string to standard output.

The terminal receiving the escape code from clear/tput interprets it and executes the command sent, such as clearing the local display. "terminal" means the local console or a terminal session (putty, xterm, etc.), possibly via ssh or telnet.

Tags:

Shell

Terminal