如何获得在bash光标位置? [英] How to get the cursor position in bash?

查看:337
本文介绍了如何获得在bash光标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash脚本,我想在一个变量的指针列。它看起来像使用ANSI转义code {} ESC [6N 是得到它的唯一途径,比如通过以下方式:

In a bash script, I want to get the cursor column in a variable. It looks like using the ANSI escape code {ESC}[6n is the only way to get it, for example the following way:

# Query the cursor position
echo -en '\033[6n'

# Read it to a variable
read -d R CURCOL

# Extract the column from the variable
CURCOL="${CURCOL##*;}"

# We have the column in the variable
echo $CURCOL

不幸的是,这个字符打印到标准输出,我想静静地做。此外,这是不很便携式...

Unfortunately, this prints characters to the standard output and I want to do it silently. Besides, this is not very portable...

有没有纯bash的方式来实现这一目标?

Is there a pure-bash way to achieve this ?

推荐答案

您必须诉诸搞鬼:

#!/bin/bash
# based on a script from http://invisible-island.net/xterm/xterm.faq.html
exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
# on my system, the following line can be replaced by the line below it
echo -en "\033[6n" > /dev/tty
# tput u7 > /dev/tty    # when TERM=xterm (and relatives)
IFS=';' read -r -d R -a pos
stty $oldstty
# change from one-based to zero based so they work with: tput cup $row $col
row=$((${pos[0]:2} - 1))    # strip off the esc-[
col=$((${pos[1]} - 1))

这篇关于如何获得在bash光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆