保存和恢复终端内容 [英] Save and restore terminal content

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

问题描述

我正在编写自动化脚本 (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 脚本中

#!/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天全站免登陆