在 bash 终端中保存更多 corsor 位置(使用 tput?)

And*_*asT 5 command-line bash cursor

我知道这会tput sc保存当前的光标位置并tput rc准确地将其恢复到tput sc被调用的位置。问题是每次tput sc调用时,它都会覆盖之前保存的位置。

有没有一种方法,以节省更多的位置,例如tput sc pos1并且tput sc pos2可与,比如说可以恢复,tput rc pos1tput rc pos2分别?(解决方案不需要使用tput,我提到它是因为它是我知道的唯一处理光标位置的命令)

如果没有,有没有办法至少在函数中本地保存光标位置,以便如果一个函数使用tput sc然后调用另一个再次运行的函数tput sc,那么每个函数在调用时都会恢复自己保存的光标位置tput rc

提前致谢。

Nyk*_*kin 6

tput命令通过终端控制序列工作,此处列出:http://sydney.edu.au/engineering/it/~tapted/ansi.html有一个用于提取当前位置的序列(查询光标位置 - \e[6n),看起来不存在在tput。要提取它,请使用:

stty -echo; echo -n $'\e[6n'; read -d R x; stty echo; echo ${x#??}
30;1
Run Code Online (Sandbox Code Playgroud)

$x现在您可以提取保存到其他变量中的行位置,并tput cup稍后使用以下命令移动光标:

$ echo $my_saved_pos
12
$ tput cup $my_saved_pos 0
Run Code Online (Sandbox Code Playgroud)


Rad*_*anu 5

您可以使用以下函数在简单数组中提取当前光标位置:

extract_current_cursor_position () {
    export $1
    exec < /dev/tty
    oldstty=$(stty -g)
    stty raw -echo min 0
    echo -en "\033[6n" > /dev/tty
    IFS=';' read -r -d R -a pos
    stty $oldstty
    eval "$1[0]=$((${pos[0]:2} - 2))"
    eval "$1[1]=$((${pos[1]} - 1))"
}
Run Code Online (Sandbox Code Playgroud)

(此功能中使用的代码源取自并改编自此答案

现在,例如,要将当前光标位置保存在 中pos1,请使用:

extract_current_cursor_position pos1
Run Code Online (Sandbox Code Playgroud)

要将当前光标位置保存在 中pos2,请使用:

extract_current_cursor_position pos2
Run Code Online (Sandbox Code Playgroud)

要查看保存在pos1和 中的光标位置pos2,您可以使用:

echo ${pos1[0]} ${pos1[1]}
echo ${pos2[0]} ${pos2[1]}
Run Code Online (Sandbox Code Playgroud)

要将光标位置移动/恢复到pos1,您必须使用:

tput cup ${pos1[0]} ${pos1[1]}
Run Code Online (Sandbox Code Playgroud)

要将光标位置移动/恢复到pos2,您必须使用:

tput cup ${pos2[0]} ${pos2[1]}
Run Code Online (Sandbox Code Playgroud)