保存和还原终端内容 [英] Save and restore terminal content

查看:145
本文介绍了保存和还原终端内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

说实话,我什至不知道从哪里开始搜索.它是来自curses库的命令吗?它是ANSI转义序列吗?我应该弄混tty吗?我被困住了,任何指针都将真正有帮助.

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.

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

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 :)

推荐答案

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

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

#!/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

这仅在具有smcuprmcup功能的终端上有效(例如,不适用于Linux控制台(=虚拟控制台)). 终端功能可以通过infocmp进行检查.

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.

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

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

注意:

如果您打算重定向输出,则可能希望将转义序列直接写到/dev/tty,以免弄脏它们stdout:

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
#...    

这篇关于保存和还原终端内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆