Wednesday, December 30, 2009

Easily add color to your Bash environment

Posted by Kallin Nagelberg

Whether you want to add some punch to your Bash prompt or emphasize some echo statements in a script, a little bit of color can go a long way. To start off you should download the scripts I have written that demonstrate most of the color options available and provide a handy function to add color to your own scripts. They are available as a TAR or a ZIP, and if you just want to view the source it is available here.

The three files in the archive are:
  • color_vars.sh - colorizing function and color variables
  • echotest.sh - a very simple example of how you could use color_vars to enhance your scripts
  • color_list - prints out a grid showing all the text/background color combinations

Once you've got them extracted you should try running echotest and color_list. echotest should produce output like:


while color_list should produce:



Be sure that your terminal window is large enough to display the grid. In a smallish window things won't line up and I can't take responsibility for what happens :)

Now that you've seen what it can do, it's time for a little explanation of how it works. I'll start by explaining how to use my color function.

Take a look at echotest.sh (it's only a few lines, and I promise nothing too scary). It starts off by sourcing color_vars.sh in order to gain access to the colorizing function as well as all the color identifiers. The next few lines use the color function to set text and background colors, and to reset back to the default terminal color when finished. Calling color with zero arguments resets to default, with one argument you can set the text color, and with two arguments the first is the text color and the second is the background color. All the possible text and background colors are declared at the top of color_vars.sh.

That's all there is to it! This should get you up and running with colorized scripts in no time. If you're interested in how the color function works it is quite simple and you should have little difficulty understanding the function's code.

note: Most modern Bash environments support the same coloring options, though for these examples I've only tested thoroughly using GNU bash v 4.0.33.





0 comments:

Post a Comment