4

clear clears the screen of the terminal.

Is there any command that can restore the original screen contents from before clear was run, effectively undoing that clear?

3 Answers3

3

There is no direct opposite of the clear command, which clears a terminal screen.

However, some implementations of a command line terminal emulator offer a scroll-back buffer. This buffer may keep previous lines of output. For example, using these commands in mintty from Cygwin to generate text and then clear the screen I find that I am able to scroll back to the previous result. However, this is implemented purely as part of a terminal emulator and is unlikely to be accessible programmatically:

yes | head -n20 | nl     # Generate 20 lines of unique output
yes n | head -n20 | nl   # And some more

20 lines of output

clear

screen cleared

After scroll-back

scroll-back buffer

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
3

If using the tmux terminal emulator/multiplexer, you could define an undoable clear as:

clear() {
  tmux capture-pane -eb c &&
    tput sc &&
    command clear "$@"
}

And unclear as:

unclear() {
  tput home && tmux show-buffer -b c && tput rc
}

Where clear captures the contents of the screen into the c buffer and saves the cursor position before clearing and unclear dumps the contents of that buffer after having moved the cursor to the home position (top-left) and then restores the cursor position.

1

If you mean undo, then there is ★nothing. Except, you can go through the command history and re-run a command. If the command is idempotent, then you will get the same result.

Footnotes: ★ nothing unless you use some sort of logging system. This logging may be part of a terminal program, or separate. It is not part of the kernel called Linux.

  • 1
    It might have to be not only the command that was idempotent but the context too. Consider ls -l file for a file that existed, followed by rm -f file a little later – Chris Davies Jul 06 '22 at 14:59