2009-05-05

Colorize Your Bash Prompt

If you're using Bash, then you're lucky enough to make your console or terminal cool by colorizing your Bash prompt. You'll also learn an easy way to make your Perl script's output colorful after reading this article.

1. Colorize Your Bash Prompt

As Bash prompt is set by $PS1, just modify its value by export.

$ vim ~/.bashrc (This is my setting)
export PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\W\[\e[m\] \[\e[1;32m\]\$\[\e[m\] '
You'll get:


Of course you can make it like whatever you want it to be.
Let's have a look at the structure of the new $PS1.
export PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\W\[\e[m\] \[\e[1;32m\]\$\[\e[m\] '
Actually it's the red letters that set the different colors. They usually appear in pairs. For example, \e[0;32m make all following text green and \e[m end this effect. Note that "\[" and "\]" around them are necessary.

To use other colors, just change the color code, e.g. 0;32 and 1;34.

2. Color Code

Here's a Perl script that will print the color code table in a clear way.
#!/usr/bin/perl print "Color\tCode\tLightColor\tCode\n", "-" x 38, "\n\e[0;30mBlack\e[m\t(0;30)\t\e[1;30mDark Gray\e[m\t(1;30)\n\e[0;31mRed\e[m\t(0;31)\t\e[1;31mLightRed\e[m\t(1;31)\n\e[0;32mGreen\e[m\t(0;32)\t\e[1;32mLightGreen\e[m\t(1;32)\n\e[0;33mBrown\e[m\t(0;33)\t\e[1;33mYellow\e[m\t\t(1;33)\n\e[0;34mBlue\e[m\t(0;34)\t\e[1;34mLightBlue\e[m\t(1;34)\n\e[0;35mPurple\e[m\t(0;35)\t\e[1;35mLightPurple\e[m\t(1;35)\n\e[0;36mCyan\e[m\t(0;36)\t\e[1;36mLightCyan\e[m\t(1;36)\n\e[0;37mLightGray\e[m(0;37)\t\e[1;37mWhite\e[m\t\t(1;37)\n";
And here's the color code table.


Now pick your favourite colors! It's so easy!
Enjoy!


3. Reference

[1] http://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/
[2] http://wiki.archlinux.org/index.php/Color_Bash_Prompt

No comments: