假设您有 GNU coreutils,一个稍微简单的方法是在这样的敏感命令中替换less
为timeout --foreground 600 less; printf '\033[?47h'; clear; printf '\033[?1049l'; stty cooked echo
。该timeout
命令在给定的持续时间后终止进程,--foreground
开关允许less
使用 TTY,并stty cooked echo
在终止后修复终端less
。如果杀死less
阻止了备用屏幕的清除和退出,则干预命令会这样做。
printf
命令中使用的转义序列适用于与DEC 兼容的终端(仿真器),例如 Xterm。您的特定终端可能会使用不同的序列来完成此任务。
一个简单的函数:
tless () {
timeout --foreground 600 less "$@"
printf '\033[?47h' # Enter alternate screen
clear
printf '\033[?1049l' # Exit alternate screen and restore cursor
</dev/tty stty cooked echo # Use in a pipe requires specifying the TTY
}
Run Code Online (Sandbox Code Playgroud)
可以大大减少打字。
感谢@meuh 指出原始版本可能无法清除或退出备用屏幕。
编辑以允许tless some-file
. 此外,该版本已经在 Linux 和 Solaris 11 上进行了测试。