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?

  • Which terminal program are you using? – Omnifarious Nov 19 '12 at 3:59

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.

| improve this answer | |
  • You are a GOD! This solved my command history problem. – stariz77 Nov 19 '12 at 4:18
  • @stariz77: No, not even a demigod really. ;-) I'm glad it fixed your problem though. Do you know how to get to info nodes to read them? – Omnifarious Nov 19 '12 at 4:38
  • I'm not sure what you mean by info nodes? If it's just a synonym for man pages, then yes. – stariz77 Nov 19 '12 at 5:47
  • 2
    @stariz77, no, info (aka Texinfo) is the standard documentation format of the GNU project. It generally contains much more detail than a manpage. Try typing the command info bash (or info info to learn about info itself). – cjm Nov 19 '12 at 7:22
  • 1
    @stariz77 - And the command to get right to the mentioned info node would be info '(bash)Printing a Prompt'. – Omnifarious Nov 19 '12 at 7:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.