PS1 problem, messing up CLI

I did a simple PS1 assignment

PS1="\e[0;31m[\W]\$ \e[m "

All I wanted to do was to change the prompt color and display only the relative path. However this messes up the CLI. For example, when browsing history with the it crops and overlaps the display. When i type a long command the cursor moves to the beginning of the screen overlapping with the prompt display itself. What have I done wrong?


That's because bash thinks the prompt is longer than it is. The escape sequence \e[0;31m for instance, gets sucked up by the terminal, which in turn turns the following text red, but bash doesn't know that. So, you have to tell bash that that sequence of characters should not be counted in the prompt's length, and you do that by enclosing it in \[ \]. I also recommend using tput instead of hardcoding terminal escape sequences.

red=$(tput setaf 1)
reset=$(tput sgr0)
PS1='\[$red\][\W]\$\[$reset\] '

See BashFAQ 53 and Terminal codes (ANSI/VT100) introduction for more.