如何在bash中获取光标位置?

时间:2010-04-04 16:16:58

标签: bash cursor

在bash脚本中,我想在变量中获取游标列。看起来使用ANSI转义码{ESC}[6n是获取它的唯一方法,例如以下方式:

# 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

不幸的是,这会将字符打印到标准输出,我希望以静默方式执行此操作。此外,这不是很便携......

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

6 个答案:

答案 0 :(得分:32)

你必须采用肮脏的技巧:

#!/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))

答案 1 :(得分:9)

您可以告诉read使用-s标志静默工作:

echo -en "\E[6n"
read -sdR CURPOS
CURPOS=${CURPOS#*[}

然后CURPOS等于21;3

答案 2 :(得分:3)

我的(两个)相同版本...

作为功能,使用ncurses的用户定义指令设置特定变量:

getCPos () { 
    local v=() t=$(stty -g)
    stty -echo
    tput u7
    IFS='[;' read -rd R -a v
    stty $t
    CPos=(${v[@]:1})
}

比现在:

getCPos 
echo $CPos
21
echo ${CPos[1]}
1
echo ${CPos[@]}
21 1

declare -p CPos
declare -a CPos=([0]="48" [1]="1")

Nota::我在第ncurses行使用 tput u7 命令:#4,希望它能保留更多可移植性,而不是通过命令使用 VT220 字符串:printf "\033[6n" ...不确定:无论如何,这对它们中的任何一个都有效:

getCPos () { 
    local v=() t=$(stty -g)
    stty -echo
    printf "\033[6n"
    IFS='[;' read -ra v -d R
    stty $t
    CPos=(${v[@]:1})
}

将在完全兼容 VT220 的TERM下工作。

更多信息

您可能在那找到了一些文档:

VT220 Programmer Reference Manual - Chapter 4

  

4.17.2设备状态报告(DSR)

     

...

Host to VT220 (Req 4 cur pos)  CSI 6 n       "Please report your cursor position using a CPR (not DSR) control sequence."

VT220 to host (CPR response)   CSI Pv; Ph R  "My cursor is positioned at _____ (Pv); _____ (Ph)."
                                              Pv =  vertical position (row)
                                              Ph =  horizontal position (column)

答案 3 :(得分:2)

为了便携性,我已经开始制作与POSIX兼容的版本,它将在像dash这样的shell中运行:

#!/bin/sh

exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
tput u7 > /dev/tty
sleep 1
IFS=';' read -r row col
stty $oldstty

row=$(expr $(expr substr $row 3 99) - 1)        # Strip leading escape off
col=$(expr ${col%R} - 1)                        # Strip trailing 'R' off

echo $col,$row

...但我似乎无法为bash的'读-d '找到可行的替代方案。没有睡眠,脚本完全错过了返回输出......

答案 4 :(得分:1)

万一其他人正在寻找这个,我在这里遇到了另一个解决方案: https://github.com/dylanaraps/pure-bash-bible#get-the-current-cursor-position

下面是带有注释的稍微修改的版本。

#!/usr/bin/env bash
#
# curpos -- demonstrate a method for fetching the cursor position in bash
#           modified version of https://github.com/dylanaraps/pure-bash-bible#get-the-current-cursor-position
# 
#========================================================================================
#-  
#-  THE METHOD
#-  
#-  IFS='[;' read -p $'\e[6n' -d R -a pos -rs || echo "failed with error: $? ; ${pos[*]}"
#-  
#-  THE BREAKDOWN
#-  
#-  $'\e[6n'                  # escape code, {ESC}[6n; 
#-  
#-    This is the escape code that queries the cursor postion. see XTerm Control Sequences (1)
#-  
#-    same as:
#-    $ echo -en '\033[6n'
#-    $ 6;1R                  # '^[[6;1R' with nonprintable characters
#-  
#-  read -p $'\e[6n'          # read [-p prompt]
#-  
#-    Passes the escape code via the prompt flag on the read command.
#-  
#-  IFS='[;'                  # characters used as word delimiter by read
#-  
#-    '^[[6;1R' is split into array ( '^[' '6' '1' )
#-    Note: the first element is a nonprintable character
#-  
#-  -d R                      # [-d delim]
#-  
#-    Tell read to stop at the R character instead of the default newline.
#-    See also help read.
#-  
#-  -a pos                    # [-a array]
#-  
#-    Store the results in an array named pos.
#-    Alternately you can specify variable names with positions: <NONPRINTALBE> <ROW> <COL> <NONPRINTALBE> 
#-    Or leave it blank to have all results stored in the string REPLY
#-  
#- -rs                        # raw, silent
#-  
#-    -r raw input, disable backslash escape
#-    -s silent mode
#-  
#- || echo "failed with error: $? ; ${pos[*]}"
#-  
#-     error handling
#-  
#-  ---
#-  (1) XTerm Control Sequences
#-      http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Functions-using-CSI-_-ordered-by-the-final-character_s_
#========================================================================================
#-
#- CAVEATS
#-
#- - if this is run inside of a loop also using read, it may cause trouble. 
#-   to avoid this, use read -u 9 in your while loop. See safe-find.sh (*)
#-
#-
#-  ---
#-  (2) safe-find.sh by l0b0
#-      https://github.com/l0b0/tilde/blob/master/examples/safe-find.sh
#=========================================================================================


#================================================================
# fetch_cursor_position: returns the users cursor position
#                        at the time the function was called
# output "<row>:<col>"
#================================================================
fetch_cursor_position() {
  local pos

  IFS='[;' read -p $'\e[6n' -d R -a pos -rs || echo "failed with error: $? ; ${pos[*]}"
  echo "${pos[1]}:${pos[2]}"
}

#----------------------------------------------------------------------
# print ten lines of random widths then fetch the cursor position
#----------------------------------------------------------------------
# 

MAX=$(( $(tput cols) - 15 ))

for i in {1..10}; do 
  cols=$(( $RANDOM % $MAX ))
  printf "%${cols}s"  | tr " " "="
  echo " $(fetch_cursor_position)"
done

答案 5 :(得分:-6)

tput命令是您需要使用的。简单,快速,无输出到屏幕。

#!/bin/bash
col=`tput col`;
line=`tput line`;