Issue
When I try to get the column and position of the cursor in a bash shell, the value returned does not match what I would think it to be.
For example when I have a prompt that looks like so:
user@machine: echo -en '\033[6n
I would expect the column to be the value of the column where the cursor was when I hit enter (in this case 32 as I'm counting what PS1 renders). However, the reported column is always 1. Confusingly, the row number is always correct.
If I then change the command to:
echo -en 'xxx\033[6n'
I then get an answer of 4.
I think I have conceptual misunderstanding of what the escape code is actually querying. What is the misunderstanding on my part? If I wanted to get the position of the cursor when I hit enter, how would I go about it?
Solution
What is the misunderstanding on my part?
You type echo -en '\033[6n'
.
The press enter.
Cursor goes to the next line.
Then bash executes the command echo -en '\033[6n
.
Then TTY outputs the cursor location. Cursor is on the next line on column 1. So the column will be 1.
I believe what is misunderstood is the expectancy that the command is executed before shifting lines up and setting cursor location to the next line. The command is executed after shifting the cursor position to the next line.
If I wanted to get the position of the cursor when I hit enter, how would I go about it?
In any case, you would not use an interactive shell. You would write and run your own program that queries the cursor location without the requirement of pressing enter and has proper logic to parse escape sequences returned by TTY.
Answered By - KamilCuk Answer Checked By - Robin (WPSolving Admin)