Strovent SystemsSign in
Reference

Clear the terminal screen and its scrollback

What clear and reset do to the screen and the scrollback, why old lines can still be there after clear, and the escape sequence that erases saved lines.

Running clear empties the visible screen. Whether the lines that scrolled off the top disappear too depends on the program that sends the command and the terminal that receives it.

The commands

  • clear clears the screen and the scrollback buffer, if there is one. It asks the terminfo entry for your TERM how to do each: the capability named clear empties the screen, and the extended capability E3 erases the scrollback.
  • clear -x does not try to clear the scrollback. Use it when you want to keep history.
  • Ctrl+L is a key, not a terminal command. The program reading your keys, such as the shell's line editor, decides what it does, so look in that program's manual.
  • reset reinitializes the terminal. It is for a terminal left in a bad state, not for tidying: see Screen modes.

The clear and E3 details are from the ncurses clear(1) manual.

The escape sequence

Underneath, erasing the saved lines is one control sequence:

printf '\033[3J'

The xterm control sequences reference lists CSI Ps J (Erase in Display): 0 erases below the cursor, 1 erases above, 2 erases the whole screen, and Ps = 3 erases the saved lines. The saved-lines value is marked as an xterm addition to the older VT100 sequence, so not every terminal implements it. To clear both the screen and the history by hand, send 2J and 3J after moving the cursor home (\033[H):

printf '\033[H\033[2J\033[3J'

The VT emulator in this app handles CSI 3 J by emptying its scrollback.

Why old lines are still there

  • The terminfo entry has no E3. The clear command then clears the screen only. Try printf '\033[3J' yourself.
  • You used clear -x. It keeps the history on purpose.
  • The terminal ignores the sequence. Scrollback can be implemented in the client, in screen or tmux, or in your terminal app. A multiplexer keeps its own history, separate from the terminal's, and has its own command to clear it. Check its manual.
  • Mosh. A Mosh client shows the host's screen, not a scrollback of its own: see Mosh or SSH?.

Sources

Spotted a mistake? Email [email protected].