This question already has an answer here:

I've tried to change my prompt by editing .bashrc:

export PS1="\e[0;32m[\u@\h \W]\$ \e[m"

This seems to work, but ctrl-r to access reverse history ends up with my typing not appearing in the same place as it will be interpreted (like this question). It is fine when using the up or down arrows to select previous commands though.

I've had a look at that question, but can't seem to work out where to apply the escape characters in my prompt. I've tried a few combinations but then I break normal text typing functionality or simple back/forwards through history.

If you could include an explanation of which instances of characters need escaping and why, that would help me (and hopefully others) learn.

marked as duplicate by Gilles, HalosGhost, techraf, roaima, Eric Renouf Dec 11 '16 at 2:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 3 down vote accepted

The shell needs to know how much space the prompt takes up on screen. Any character sequence which takes up no space on screen needs to be escaped using \[ and \]: this includes escape sequences such as those used to set the colour, or give the terminal window a title, or move the cursor...

Thus in your case:

export PS1="\[\e[0;32m\][\u@\h \W]\$ \[\e[m\]"

tells the shell that only [\u@\h \W]$ actually take up space on the screen.

  • Ah great - that makes a lot of sense. The other question didn't really offer that level of explanation of the why. – SilverlightFox Dec 9 '16 at 16:07

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