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.

| improve this answer | |
  • 1
    Thanks for your perfect description I had this problem several times and never knows where the problem was. – Betlista Jan 5 '13 at 0:04
  • +1, same here. For those blindly testing this solution and it doesn't work, it's worth mentioning here that there's another syntax described in the BashFAQ link for escaping colors within functions, \001 \002. – Stephen Niedzielski Apr 24 '15 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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