Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and restore terminal content

I am writing automation scripts (perl/bash). Many of them benefit from some basic terminal GUI. I figured I'd use standard ANSI sequences for basic drawing. Before drawing in terminal I do clear but doing that I lose some terminal command history. I want to be able to restore terminal command history when my program exists. Many terminal programs (e.g. less, man, vim, htop, nmon, whiptail, dialog etc) do exactly that. All of them restore terminal window bringing the user back to where he was prior to calling the program with all the history of commands previously executed.

To be honest I don't even know where to start searching. Is it a command from curses library? Is it an ANSI escape sequence? Should I mess with tty? I am stuck and any pointers would be really helpful.

EDIT: I'd like to clarify that I am not really asking "how to use the alternative screen". I am looking for a way to preserve terminal command history. One possible answer to my question could be "use alternative screen". The question "what is alternative screen and how to use it" is a different question which in turn already has answers posted elsewhere. Thanks :)

like image 225
oᴉɹǝɥɔ Avatar asked Nov 26 '15 02:11

oᴉɹǝɥɔ


1 Answers

You should use the alternate screen terminal capability. See Using the "alternate screen" in a bash script

An answer to "how to use the alternate screen":

This example should illustrate:

#!/bin/sh
: <<desc
Shows the top of /etc/passwd on the terminal for 1 second 
and then restores the terminal to exactly how it was
desc

tput smcup #save previous state

head -n$(tput lines) /etc/passwd #get a screenful of lines
sleep 1

tput rmcup #restore previous state

This'll only work on a terminal has the smcup and rmcup capabilities (e.g., not on Linux console (=a virtual console)). Terminal capabilities can be inspected with infocmp.

On a terminal that doesn't support it, my tput smcup simply return an exit status of 1 without outputting the escape sequence.


Note:

If you intend to redirect the output, you might want to write the escape sequences directly to /dev/tty so as to not dirty your stdout with them:

exec 3>&1 #save old stdout
exec 1>/dev/tty #write directly to terminal by default
#...
cat /etc/passwd >&3 #write actual intended output to the original stdout
#...    
like image 180
PSkocik Avatar answered Sep 29 '22 15:09

PSkocik