Leaderboard ad


Using Color in the Output of Your Bash Script

Let's face it, bash scripts are mostly boring and the output it usually drab and hard to read, especially when there is a lot of it. That's why when I write a script I like to add some color to the output.  Colorizing the output can bring attention to errors, emphasized an important piece of output, or just jazz us a countdown.

The first step in adding color to your bash scripts is understanding the echo command and it's interpretation of backslash-escaped characters.  By using the -e option with echo, you can enable some interesting features to help format your output. In this article we will be using the "enable interpretation" or -e option to colorize our bash output.  You can also use it to sound a terminal bell or format your output in a cleaner fashion.  For a list of backslash-escaped characters see the echo man page.

The most popular colors I use are red and green, often to express something good or bad (error or success) in scripts.  I start by putting the ANSI codes for these colors, and one for no color, into variables.  This makes the colorization easy to use throughout a script.



Now that you have your variables set, you can all them out using echo or printf, like so.

echo -e "The Italian flag colors are ${GREEN}GREEN${RESET}, ${WHITE}WHITE${RESET}, and ${RED}RED${RESET}."

or you can use them to show success and errors like so:

grep -i savona /etc/passwd
if [ "$?" == "0" ]; then
echo -e "${GREEN}User exists in passwd file${RESET}"
echo -e "${RED}User does NOT exist in passwd file${RESET}"

Of course that is a VERY simple example, but you can use your creativity and come up with some really interesting ways to use ANSI color codes.

Here is a list of basic color codes you can use:

Black        0;30
Red          0;31
Green        0;32
Yellow       0;33
Blue         0;34
Magenta      0;35
Cyan         0;36
Light Gray   0;37

No comments:

Post a Comment