Tuesday, October 5, 2010

Terminal Prompt Coloring and Line-Wrap Issues

The other day I was look scrolling back through my terminal window and needed to be able to pick out the prompts so I could differentiate output from different commands.  So I edited my ~/.profile file and added this to the bottom:

export PS1="[\e[36m\u\e[33m@\e[32m\W\e[0m]\e[32m > \e[0m"

To give me a prompt that looks like:



However, whenever I would use a command that was longer than the line, and it needed to wrap, the formatting would get all funky and the terminal wouldn't correctly represent either the command that I had entered or the position of the cursor.

I asked a colleague of mine about it and he suggested that it was because of the coloring of the prompt and that the non-printable characters (the ones that are for coloring) caused the line editor to display incorrectly. So I researched it further to realize that my PS1 string was missing the non-printable character string delimiters: \[ ... \]

So I edited my PS1 variable, wrapping all non-printing characters with \[ and \]

export PS1="[\[\e[36m\]\u\[\e[33m\]@\[\e[32m\]\W\[\e[0m\]]\[\e[32m\] > \[\e[0m\]"


and PRESTO line wrapping issues are gone!

So, remember: if you ever see weirdness in the terminal formatting check out your prompt definition first!

For a decent guide to creating a nice prompt check out Prompt Magic.