How to stop `clear` from clearing scrollback buffer

This took me a while to figure out so I guess I should share how I got this to work.

If you type "man clear" you will see that the manual states:

clear clears your screen if this is possible, including its scrollback buffer (if the extended "E3" capability is defined).

We are going to remove this E3 capability:

First, find out the type of your terminal:

echo $TERM

For me this resulted in "xterm-256color". Whatever it outputs, remember it.

Now enter the command:

infocmp -x xterm-256color > tempfile

Where you obviously replace xterm-256color with the output from the first command. This will output the extended capabilities for this terminal type to 'tempfile'.

Now edit this newly created file. You are looking for:

E3=\E[3J,

Find this and just remove it. The entire thing, so if it looked like:

    ...
    Cs=\E]12;%p1%s\007, E3=\E[3J,
    Ms=\E]52;%p1%s;%p2%s\007, Se=\E[2 q, Ss=\E[%p1%d q,
    ...

It should now look like:

    ...
    Cs=\E]12;%p1%s\007,
    Ms=\E]52;%p1%s;%p2%s\007, Se=\E[2 q, Ss=\E[%p1%d q,
    ...

Save the file. And from your terminal execute:

sudo tic -x tempfile

This will load your modified terminfo and store it. restart your terminal and clear should now no longer remove the scrollbuffer


What you want is to type CTRL+L instead of clear.

This will send a "Form Feed" to the terminal. Basically it will move everything up the height of the terminal window clearing the screen without affecting your scrollback.


This answer builds off of stingray's answer (which he did some really good work on) and is meant to complete it.

1 - To clear without loosing scrollback, enter the following command in console (no need for python as suggested in stringray's answer):

printf '\33[H\33[2J'

2 - To avoid having to memorize this, you can edit your .bashrc file to make an alias for it. I would call the alias clear. In bash, enter:

nano ~/.bashrc

And add this line at the end:

alias clean="printf '\33[H\33[2J'"

I also like to add div (for divider):

alias div='echo;echo "------------------------------------------------------------------------------";echo;echo;echo;echo;echo;echo;echo;echo;echo;echo;echo;echo "------------------------------------------------------------------------------";clean'

This makes it so that when you do the div command, it enters two dividers with 10 new lines between them, followed by a clean command. This will make so that when you are scrolling back, you'll know exactly where you used div.

You can change the sudo bash behavior by doing sudo su before the procedure I listed.

I would recommend this over bashBedlam's answer of using tic, as editing .bashrc:

1) it doesn't require sudo privileges and can be easilly taken on the go.

2) only affects your user (not all users will want the modified clear function)

3) will survive updates which usually don't touch bashrc