Some time back I found a nifty little function to nicely and neatly add color to my bash prompt, and to do so in a readable and easily editable way. I forget the site where I originally saw the function, so I apologize to its author for displaying it here without attribution, but it’s certainly made my life easier; I have my prompt set to display the time, the user name and host name where I’m logged in, the directory I’m in, and the root/other token. I’m a visual kind of guy, too, so I alter the user/hostname so that it’s a different color for each of the boxes I’m regularly acessing at home.
On GNU/Linux and OS X, the two operating systems I’m most frequently using, the prompt the user most often sees is stored in a variable named PS1
. PS1 contains some pretty boring default values for most OSs, especially OS X, but fortunately we can make it a lot more informative and useful by modifying its value in the .bashrc
file in your home directory, assuming you’re using bash as your shell—if you’re familiar enough with Unix and/or BSD to use a shell other than bash, you probably have your own ideas what PS1 should look like and probably think including colors in a prompt makes the baby Stallman cry. Or you use emacs for your operating system.
“Wait,” you say, “my .bashrc
file? Why not put whatever shell voodoo you’re about to list out into .bash_profile
instead?” Great question! For a great answer, check out John Staiger’s succinct explanation, but the quick summary is because .bashrc
is where you want to put things like prompt variables. Because it is. In fact, your .bash_profile
file should probably have this, and only this, in it:
(Again, if you know enough about Unix and/or BSD to feel otherwise, then you’ve probably already quit reading and gone back to LISP programming or something.)
So, to create a nice and easy framework to mix and match colors in your prompt, add the following to the end of .bashrc
:
If you’re using Ubuntu Linux, either desktop or server, there will likely already be some additional scriptwork in .bashrc
to detect whether or not the terminal has the ability to display a colored prompt and then to use or not use a color prompt; if so, find the existing export PS1=
line, comment it out, and replace it with the above.
The PS1 statement will get you my preferred prompt, which you should change to suit you (and a good list of bash prompt variables can be found right here). The nifty part is that rather than futzing around with a bunch of ANSI escape sequences to represent color, the major terminal window colors and their bold variants are already listed out, so you can plug them into your PS1 statement as friendly variable names instead of as codes.
Discussion topic for the original blog entry at: http://blog.bigdinosaur.org//easy-ps1-colors