Adding colors to Bash scripts

I recently wrote a post-receive git hook for a server and I wanted to easily distinguish my hook's output from git information. This led me to look into colorizing bash output.

By using ANSI color escape codes, we can add color to output strings. The ANSI standard specifies certain color codes;

ColorForeground CodeBackground Code
Black3040
Red3141
Green3242
Yellow3343
Blue3444
Magenta3545
Cyan3646
Light Gray3747
Gray90100
Light Red91101
Light Green92102
Light Yellow93103
Light Blue94104
Light Magenta95105
Light Cyan96106
White97107

To change the color of the text, what we want is the foreground code. There are also a few other non-color special codes that are relevant to us:

CodeDescription
0Reset/Normal
1Bold text
2Faint text
3Italics
4Underlined text

The echo command prints out text. We need to tell it that we're working with special ANSI codes, not just regular characters. This can be accomplished by adding a \e at the beginning to form an escape sequence. The escape sequence for specifying color codes is \e[COLORm (COLOR represents our color code in this case). By default, echo does not support escape sequences. We need to add the -e option to enable their interpretation.

To print red text, therefore, we could have

echo -e "\e[32Red text\e[0m"

The \e[0m means we use the special code 0 to reset text color back to normal. Without this, all other text you print out after this would be red.

This works, but it would be more readable if we store the color codes in variables and use those instead.

RED="\e[31m"
ENDCOLOR="\e[0m"

echo -e "${RED}Red text${ENDCOLOR}"

Putting all these together, we could have a script like this

#! /usr/bin/env bash

RED="\e[31m"
GREEN="\e[32m"
ENDCOLOR="\e[0m"

echo -e "${RED}This is some red text, ${ENDCOLOR}"
echo -e "${GREEN}And this is some green text${ENDCOLOR}"

Demoing this

We can combine escape codes to get more fancy output.

#! /usr/bin/env bash

RED="31"
GREEN="32"
BOLDGREEN="\e[1;${GREEN}m"
ITALICRED="\e[3;${RED}m"
ENDCOLOR="\e[0m"

echo -e "${BOLDGREEN}Behold! Bold, green text.${ENDCOLOR}"
echo -e "${ITALICRED}Italian italics${ENDCOLOR}"

Another one

You can use these in any number of ways to make your scripts less monotonous. The combinations are up to you. Happy scripting!