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, emphasizes an important piece of output, or just jazzes up 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.

GREEN='\033[0;32m'
RED='\033[0;31m'
WHITE='\033[0;37m'
RESET='\033[0m'

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

#!/bin/bash
GREEN='\033[0;32m'
RED='\033[0;31m'
WHITE='\033[0;37m'
RESET='\033[0m'
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:

#!/bin/bash
GREEN='\033[0;32m'
RED='\033[0;31m'
WHITE='\033[0;37m'
RESET='\033[0m'
grep -iw savona /etc/passwd
if [ "$?" == "0" ]; then
echo -e "${GREEN}User exists in passwd file${RESET}"
else
echo -e "${RED}User does NOT exist in passwd file${RESET}"
fi

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

Read more about ANSI Escape Codes on Wikipedia.