保存并恢复终端内容

oᴉɹ*_*ǝɥɔ 8 linux terminal ansi-escape

我正在编写自动化脚本(perl/ bash).其中许多受益于一些基本的终端GUI.我想我会使用标准ANSI序列进行基本绘图.在绘制终端之前我做了clear但是这样做会丢失一些终端命令历史记录.我希望能够在我的程序存在时恢复终端命令历史记录.许多终端程序(例如less,man,vim,htop,nmon,whiptail,dialog等)这样做.所有这些都恢复终端窗口,使用户返回到他之前调用程序的位置,其中包含先前执行的所有命令历史记录.

说实话,我甚至不知道从哪里开始搜索.这是来自curses图书馆的命令吗?这是ANSI逃脱序列吗?我该捣乱tty吗?我被卡住了,任何指针都会非常有用.

编辑:我想澄清一点,我并不是在问"如何使用替代屏幕".我正在寻找一种方法来保存终端命令历史.我的问题的一个可能的答案可能是" 使用替代屏幕"."什么是替代屏幕以及如何使用它 "的问题是一个不同的问题,而这个问题又已经在其他地方发布了答案.谢谢 :)

PSk*_*cik 8

您应该使用备用屏幕终端功能.请参阅 在bash脚本中使用"备用屏幕"

"如何使用备用屏幕"的答案:

这个例子应该说明:

#!/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
Run Code Online (Sandbox Code Playgroud)

这只能在终端上运行smcuprmcup具有功能(例如,不在Linux控制台(=虚拟控制台)).终端功能可以通过检查infocmp.

在不支持它的终端上,我tput smcup只返回退出状态1而不输出转义序列.


注意:

如果您打算重定向输出,可能需要直接编写转义序列,/dev/tty以免弄乱stdout它们:

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
#...    
Run Code Online (Sandbox Code Playgroud)