How to get the terminal to regurgitate the previous output text from past commands? Is this even possible

command linehistorypipeterminal

I just ran a job that takes several hours, and I forgot to pipe that text into a text file.

pseudocode:

echo [previous text output] > OutputHistory.txt

Additionally, I can't just "copy and paste" what was in my terminal because 1) the display omits important formatting characters like "\t", and 2, I may have closed the terminal window.

Is this possible with any Unix commands?

Best Answer

This is impossible in general. Once an application has emitted some output, the only place where this output is stored is in the memory of the terminal. To give an extreme example, if this is the 1970s the terminal is a hardcopy printer, the output isn't getting back into the computer without somebody typing it in.

If the output is still in the scrolling buffer of your terminal emulator, you may be able to get it back, but how to do so depends on the terminal, there's no standard way. Tabs may or may not have been converted into spaces at that point. Whether formatting information (colors, bold, etc.) can be retrieved and in what format depends on the terminal. With most terminals, there's no easy or foolproof way to find where the command's output started and ended.

If you plan in advance, you can record the command's output transparently with script. Running script mycommand.log mycommand may be different from mycommand 2>&1 | tee mycommand.log because with script, the command is still writing to a terminal.

A compromise is to always run long-lived commands inside screen or tmux. Both have a way to dump the scrollback buffer to a file, and they have the added bonus that you can disconnect from the session without disrupting the program's execution and reconnect afterwards.