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 ?
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.
$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.
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.
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.
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))
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With