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?

4
  • ctrl-z to suspend a task OR undo OR something else? Feb 5, 2022 at 11:54
  • 1
    What would you expect to be the opposite of clearing the screen? Feb 5, 2022 at 12:12
  • 1
    @roaima I expect to see previous results in my terminal. the clear command removes results and clears the screen. I want to take it back and see that result. Feb 5, 2022 at 12:20
  • @ctrl-alt-delor undo Feb 5, 2022 at 12:22

3 Answers 3

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

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
  • 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 Jul 6, 2022 at 14:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .