Search code examples
bashshellttystty

Shell script capturing cursor terminal position on mac produces extra characters


I use the answer in https://askubuntu.com/questions/366103/saving-more-corsor-positions-with-tput-in-bash-terminal as a shell script, which works for me in extracting the current position on the terminal.

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))"
}

extract_current_cursor_position pos1
extract_current_cursor_position pos2

echo ${pos1[0]} ${pos1[1]}
echo ${pos2[0]} ${pos2[1]}

However, on the Mac machine, it produces extra -en with some new lines and spaces as shown below.

-en 
    -en 
        23 4
23 8

How could I avoid outputting the extra -en and new lines and extra spaces


Solution

  • Use printf instead of echo -en:

    printf '\033[6n' > /dev/tty
    

    -e and -n flags for echo are not shell standards and not all shells implement them. Some shells (including the one you are using) just echo them as though they were ordinary arguments.

    printf is a shell standard. It automatically expands standard backslash escape codes in its format, and also prints a newline only if you tell it to (usually by putting a \n in the format). It can also do lots of other useful things, like pad values to a specific length.