how to fix the color PS1 linewrap problem

caveat this probably only works for ksh and derivatives like bash. i have only tested in xterms running bash on linux, bsd, and mac.

when colorizing a PS1 prompt under bash, the extra characters get counted towards the line length, so that commands which exceed the terminal width screw up the display. the solution is to wrap the non-printable characters in brackets to make the shell ignore them when counting.

example .bashrc snippet

this prints the hostname in red, curdir in green, and prompt character, $, in yellow. it contains an additional 30 characters of VT escape codes. however, commands that exceed the terminal width behave themselves, and work just as well as their shorter counterparts. two things to note:

  1. double quotes are used since the colors are previously defined as shell variables for readability (for ease of maintenance).

  2. the double quotes force the use of double backslash characters; one to escape the other.

# 0-7 == black, red, green, yellow, blue, magenta, cyan, white
PS1="\\[$red\\]\\h\\[$norm\\] \\[$green\\]\\w\\[$norm\\] \\[$yellow\\]\\$\\[$norm\\] "
unset blue ; unset green ; unset red ; unset yellow ; unset norm
export PS1

that’s all folks!
Sat Jan 6 13:25:01 PST 2018