If you access multiple servers throughout the work day, then being able to tell which one you are working with at a glance based on a color scheme can be very useful. Today’s SuperUser Q&A post helps a reader achieve a colorful nirvana in his work environment.

Today’s Question & Answer session comes to us courtesy of SuperUser—a subdivision of Stack Exchange, a community-driven grouping of Q&A web sites.

The Question

SuperUser reader nitins wants to know how to make the Bash Prompt change colors when logged into a server:

How do you make the Bash Prompt change colors when logged into a server?

The Answer

SuperUser contributor Matei David has the answer for us:

Have something to add to the explanation? Sound off in the comments. Want to read more answers from other tech-savvy Stack Exchange users? Check out the full discussion thread here.

Notes

Do not set PS1 if it is not already set (i. e. if the shell is not interactive). Testing to see if PS1 is “non-empty” is a very common way to find out if the shell is interactive and you do not want to confuse programs that do that (arguably, a more accurate test is checking to see if $- contains i). If you want this code to run when logging into a remote server, you should have one of the profile files always source ~/. bashrc (I am assuming you know that). In PS1, the escape codes must be enclosed in […]. [033[m resets the foreground and background to their defaults, so here :\w appears in the terminal foreground/background. [033[48;5;XXXm\033[38;5;YYYm sets the background/foreground to XXX/YYY. For a script that dumps the available colors, try colortest. To check and see what the Bash Prompt would look like, use: echo -e “<\033[48;5;16m\033[38;5;196mhost\033[m:dir>$ “

Image Credit: Emx (Wikipedia)