Some notes on computer stuff

An issue with colour prompt in bash

October 9, 2012
[bash] [shell] [terminal] [color] [prompt] [issue]

Prehistory

Once I read somewhere that it's possible to add some colours to your shell's (bash in my case) prompt using escape sequences. I thought that it will greatly decrease time one spend finding the beginning of a command that was just run. Prompt colouring is also useful to distinguish between root and regular user prompt. So after some experiments with echo command, I added this line to my ~/.bashrc file:

# green command prompt
export PS1="\033[32m[\\w]\\$ \033[0m"

And this to /root/.bashrc:

# red command prompt
export PS1="\033[31m[\\w]\\$ \033[0m"

I liked it a lot, but after some time noticed strange issues with long command lines. I tried to live with it, but after quite long period of time removed the colouring, since it made using long commands a hell.

Nowadays

All described above was a lot time ago, until suddenly I saw a link to this page in one of comments on HabraHabr. And now I finally know how to add colours to bash prompt not having that weird behaviour with long command lines. One just needs to enclose all non-printable characters in \[ and \], so that bash wont count them as part of prompt string. Now my .bashrc files contain this:

# green command prompt
export PS1="\\[\033[32m\\][\\w]\\$ \\[\033[0m\\]"

And this to /root/.bashrc:

# red command prompt
export PS1="\\[\033[31m\\][\\w]\\$ \\[\033[0m\\]"

I think no one will argue that this makes work in terminal a bit nicer.