How to get the cursor position in bash?

后端 未结 6 2221
遥遥无期
遥遥无期 2020-11-27 02:46

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 fo

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 03:33

    My (two) version of same...

    As a function, setting specific variable, using ncurses's user defined comands:

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

    Than now:

    getCPos 
    echo $CPos
    21
    echo ${CPos[1]}
    1
    echo ${CPos[@]}
    21 1
    
    declare -p CPos
    declare -a CPos=([0]="48" [1]="1")
    

    Nota: I use ncurses command: tput u7 at line #4 in the hope this will stay more portable than using VT220 string by command: printf "\033[6n"... Not sure: anyway this will work with any of them:

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

    will work exactly same, while under VT220 compatible TERM.

    More info

    You may found some doc there:

    VT220 Programmer Reference Manual - Chapter 4

    4.17.2 Device Status Report (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)
    

提交回复
热议问题