Bash – PS1 Prompt Overwrites First Line

bashshell

I have played around with PS1 and PROMPT_COMMAND in bash to create a zsh-style right side prompt. I have a solution who almost works.

The problem is that if I write a long line of input, the second line overwrites the first one. The third line will appear nicely on a new line.

Maybe some line counter are of-by-one because my cursor movement, or is this a limitation/bug?

A simple example:

export PS1="prompt>\[\033[s\033[10C\]test\[\033[u\]"

Print prompt>, save position, move 10 characters to the left, print test, restore position.

The prompts looks nice and works perfectly, until i write more then one line of text.

Example 1, expected behaviour:

------------------------------------
prompt>          test
prompt>ls        test
files...
prompt>1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
26 27 28

Example 2, current behaviour:

------------------------------------
prompt>          test
prompt>ls        test
files...
14 15 16 17 18 19 20 21 22 23 24 253
26 27 28

Best Answer

Ah, of course. Test should not be counted as a visible character and should be included between \[ and \].

Working example:

export PS1="prompt>\[\033[s\033[10Ctest\033[u\]"

The reason was because if bash count test as a visible character it will assume it's left if the cursor and the calculation of available characters left on the current line will be off by four characters (length of 'test').

Related Question