Save and restore terminal content

风格不统一 提交于 2019-11-29 13:35:17
PSkocik

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
#...    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!