Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

linux - How can I get position of cursor in terminal?

I know I may save position using tput sc, but how can I read it's position to the variable? I need the number of row. I don't want to use curses/ncurses.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Example:

~$ echo -e "33[6n"

EDITED:

You should make sure you are reading the keyboard input. The terminal will "type" just the ESC[n;mR sequence (no ENTER key). In bash you can use something like:

echo -ne "33[6n"            # ask the terminal for the position
read -s -d[ garbage          # discard the first part of the response
read -s -d R foo              # store the position in bash variable 'foo'
echo -n "Current position: "
echo "$foo"                   # print the position

Explanation: the -d R (delimiter) argument will make read stop at the char R instead of the default record delimiter (ENTER). This will store ESC[n;m in $foo. The cut is using [ as delimiter and picking the second field, letting n;m (row;column).

I don't know about other shells. Your best shot is some oneliner in Perl, Python or something. In Perl you can start with the following (untested) snippet:

~$ perl -e '$/ = "R";' -e 'print "33[6n";my $x=<STDIN>;my($n, $m)=$x=~m/(d+);(d+)/;print "Current position: $m, $n
";'

For example, if you enter:

~$ echo -e "z033[6n"; cat > foo.txt

Press [ENTER] a couple times and then [CRTL]+[D]. Then try:

~$ cat -v foo.txt
^[[47;1R

The n and m values are 47 and 1. Check the wikipedia article on ANSI escape codes for more information.

Before the Internet, in the golden days of the BBS, old farts like me had a lot of fun with these codes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...