Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the cursor position in bash?

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...

Is there a pure-bash way to achieve this ?

like image 928
nicoulaj Avatar asked Apr 04 '10 16:04

nicoulaj


People also ask

How do I get cursor position in terminal?

At ANSI compatible terminals, printing the sequence ESC[6n will report the cursor position to the application as (as though typed at the keyboard) ESC[n;mR , where n is the row and m is the column.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I move my cursor in bash?

Move Cursor on The Command LineCtrl+A or Home – moves the cursor to the start of a line. Ctrl+E or End – moves the cursor to the end of the line. Ctrl+B or Left Arrow – moves the cursor back one character at a time. Ctrl+F or Right Arrow – moves the cursor forward one character at a time.

What is if [- Z in bash?

Use the -z Flag in Bash The -z flag is a parameter that checks if the length of a variable is zero and returns true if it is zero. In the example below, the -z flag is used with the test command, and it is tested whether the given string is empty. Bash.


2 Answers

You have to resort to dirty tricks:

#!/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)) 
like image 76
Dennis Williamson Avatar answered Sep 28 '22 10:09

Dennis Williamson


You could tell read to work silently with the -s flag:

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

And then CURPOS is equal to something like 21;3.

like image 21
BSK Avatar answered Sep 28 '22 09:09

BSK