Why does this PS1 value cause unexpected behaviour?

Possible Duplicate:
Why is my bash prompt getting bugged when I browse the history?

I have set my PS1 variable in .bashrc to be the following:

PS1='e[35m[W]:e[0m '

It achieved what it was intended to (change the color of the prompt which displays cwd inside [] and before :), but when I search through my command history, sometimes parts of commands that I cycle over become attached to the prompt. For example:

[~]: echo "something"
[~]: date
Sun Nov 18 17:07:54 PST 2012
[~]: sudo apt-get install vim

Now, say I want to return to my echo "something" command, I press up and get

[~]: sudo apt-get install vim

I press up again and this happens

[~]: sudo apt-date

up again

[~]: sudo apt-echo "something"

and if I delete everything on the command line by pressing backspace, it deletes all the way back to

[~]: sudo apt-

It has no affect on the command. For example, the line [~]: sudo apt-date will still print the output of date etc. Why is this happening and how can I achieve the desired prompt without the side effects?

Asked By: stariz77


What’s going on is that Bash is getting confused about the number of printing characters in your prompt. It sends cursor positioning sequences to the terminal to position the cursor properly for doing command history and such. It needs to have a good idea of where the cursor actually is after printing the prompt.

Try setting your prompt to this:

PS1='[e[35m][W]:[e[0m] '

It should now work as expected.

The [ and ] pairs tell Bash that the stuff between them is a non-printing escape sequence and won’t actually move the cursor forward. It will then correctly guess the cursor position and do a proper replacement when going through your command history.

This information can be found in the info node (bash)Printing a Prompt.

Edit: In newer versions of bash this has changed to (bash)Controlling the Prompt.

Answered By: Omnifarious
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.