bash - 如何获取 tput smcup/rmcup 设置的屏幕状态?

标签 bash terminal xterm tput

虽然我知道 tput rmcup 从“备用屏幕”(在 man 5 terminfo 中称为“cup 模式”)返回并恢复保存的屏幕,但它确实有重新定位光标的副作用。

因此,如果调用 tput smcuptput rmcup 会恢复屏幕并重新定位光标,但如果您随后再输入一些命令或按 Enter 几次,然后再次使用tput rmcup,光标返回到原来保存的位置。

一个用例是在重放终端记录的 bash 脚本中[使用 scriptreplay]:如果脚本提前结束而没有[相当于]调用 tput rmcup 那么我希望能够在我的 bash 脚本中检测到它并自动调用 tput rmcup

简而言之,我希望能够确定当前的屏幕状态是什么;即,它是“备用屏幕”还是“正常屏幕”?

最佳答案

如果您使用 xterm,那么您可以询问它正在使用什么模式。尽管备用屏幕功能是 xterm 功能而不是“DEC”,但该设置与 XTerm 控制序列中描述的 DECSET 模式分组。 :

CSI ? Pm h
          DEC Private Mode Set (DECSET).
...
            Ps = 1 0 4 7  -> Use Alternate Screen Buffer, xterm.  This
          may be disabled by the titeInhibit resource.
            Ps = 1 0 4 8  -> Save cursor as in DECSC, xterm.  This may
          be disabled by the titeInhibit resource.
            Ps = 1 0 4 9  -> Save cursor as in DECSC, xterm.  After sav-
          ing the cursor, switch to the Alternate Screen Buffer, clear-
          ing it first.  This may be disabled by the titeInhibit

DECRQM可以使用控件来查询终端:

CSI ? Ps$ p
          Request DEC private mode (DECRQM).  For VT300 and up, reply
          DECRPM is
            CSI ? Ps; Pm$ y
          where Ps is the mode number as in DECSET/DECSET, Pm is the
          mode value as in the ANSI DECRQM.

也就是说,您的脚本可以

printf '\033[?1049$p'

并读回结果,期望类似于 \033[?1049;1$y

这是一个快速演示:

#!/bin/sh                                                                      

unexpected() {
        result=$(echo "$check"|sed -e 's/^@/\\033/')
        printf '? unexpected reply: %s\n' "$result"
        exit 1
}

exec </dev/tty
old=`stty -g`
stty raw -echo min 0  time 5
printf '\033[?1049$p'
read status
stty $old

if [ -n "$status" ]
then
        check=$(echo "$status" |tr '\033' '@')
        if [ "$check" != "$status" ]
        then
                case "$check" in
                '@[?1049;1$y')
                        echo "alternate screen"
                        ;;
                '@[?1049;2$y')
                        echo "normal screen"
                        ;;
                *)
                        unexpected
                        ;;
                esac
        else
                unexpected
        fi
else
        echo "? no reply from terminal"
fi

当然,如果您不使用 xterm,您的情况可能会有所不同......

关于bash - 如何获取 tput smcup/rmcup 设置的屏幕状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460018/

相关文章:

Java ProcessBuilder 在传递参数时使用字符串中的句点而不是斜杠

python - 如何连接到只支持 xterm 终端的 linux 服务器

linux - 查找最大值和最小值并打印文件中的行

linux - diff 命令不起作用(参数麻烦)

bash - 使用打开的终端窗口目录路径在 OSX(Snow Leopard) 中打开一个新的终端选项卡

node.js - cucumber 测试失败,但 travis build 仍然通过

vim - MobaXterm : screen freezing

python - 如何在 IPython pandas 中配置显示输出

android - 找不到命令 'lint'

Linux脚本在shell脚本中捕获终端