How to reset the scrollback in the terminal via a shell command

bashcommand lineterminal

When using Terminal.app, you can clear the screen by using the shell builtin clear or by pressing ^+L (Control-L).

However, all this does is push the current screen content back one screen height and reset the cursor/input at the first line. Meaning you can still scroll back and see it.

What you are also able to do, is reset your entire scrollback by pressing +K (Command-K).

After you've done this, you cannot scroll back at all.

In certain situations (notably, before running screen or vim), I'd like to reset the scroll back before the command actually executes.

Is there a command (like clear) that is implemented in OS X that allows me to do this? Given the existence of pbcopy and pbpaste, I'm thinking something similar might exist that will allow me to do this.

Best Answer

Terminal supports an extension of the ED (Erase in Display) escape sequence to erase the scroll-back. It is also supported by xterm. The ED command, described in the VT100 manual, accepts these values for the Ps parameter:

ESC [ Ps J

Parameter   Parameter Meaning

0           Erase from the active position to the end of the screen
1           Erase from start of the screen to the active position
2           Erase all of the display

Terminal (and xterm) adds:

3           Erase the scroll-back (aka “Saved Lines”)

Note that this only erases the scroll-back, not the screen. This allows you to erase one or the other, or both by sending two escape sequences.

For example, you can clear the screen and the scroll-back with the following shell command: clear && printf '\e[3J'

(The clear command looks up the appropriate sequence for clearing the screen for the current terminal, but the “erase scroll-back” escape sequence is custom and must be hard-coded. If you put this in a shell script that you don’t know for certain will only ever be run with Terminal, you should check that $TERM_PROGRAM is Apple_Terminal before sending it.)