您应该使用 终端功能。请参见在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
这只能在具有smcup
和rmcup
功能的终端上使用(例如,不能在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
#...