How to get the cursor position in bash?

后端 未结 6 2223
遥遥无期
遥遥无期 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:20

    In the interests of portability I've had a go at making a vanilla POSIX-compatible version that will run in shells like dash:

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

    ...but I can't seem to find a viable alternative for bash's 'read -d'. Without the sleep, the script misses the return output entirely...

提交回复
热议问题