Many times, you might have have tempted to put some colors in your output of shell scripts.

Let’s learn how it is done.

1. Basic Example

We can use escape codes to show colors… e.g. like this:

1echo -e     '\033[1;34m Bold    Blue foreground \033[0m'
2echo -e     '\033[0;96m Normal  Bright Cyan Background \033[0m'
3echo -e '\033[0;91;103m Normal  Bright Red Foreground, Bright Yellow Background \033[0m'

The output would look like this:

Image

You can try to run the same on your bash prompt.

Let’s understand what is happening here.

  1. echo -e : This is where we tell echo command that escape codes are going to be used. Else, it will just print the string as it is without any processing.

  2. \033[ Is where the escape starts and m Is the marker till which the pattern exists.

    Please note, Sometimes, \033[ is also written as \e[

  3. So, what does 1 and 34 mean here? Something to do with Bold and Blue…. :-)

    Let’s see the table of values, and re-visit this example.

2. Escape values and it’s codes

Let’s see different codes for each values of formatting and colors.

2.1. Values for formatting

Format Code
Normal 0
Bold 1
Italic 3
Blink 5
Underline 4
Dimmed 2

2.2. Values for ForeGround Colors

Foreground Color Code
Black 30
Red 31
Green 32
Yellow 33
Blue 34
Magenta 35
Cyan 36
White 37
Grey 90
Bright Red 91
Bright Green 92
Bright Yellow 93
Bright Blue 94
Bright Magenta 95
Bright Cyan 96
Bright White 97

2.3. Values for Background Colors

Background Color Code
Black 40
Red 41
Green 42
Yellow 43
Blue 44
Magenta 45
Cyan 46
White 47
Grey 100
Bright Red 101
Bright Green 102
Bright Yellow 103
Bright Blue 104
Bright Magenta 105
Bright Cyan 106
Bright White 107

3. Same example, again

Let’s see the same example, but little more readable.

1COLOR_RESET="\033[0m"
2COLOR_BOLD_FG_BLUE="\033[1;34m"
3COLOR_FG_BRIGHT_CYAN="\033[0;96m"
4COLOR_FG_BRIGHT_RED_BG_BRIGHT_YELLOW="\033[0;91;103m"
5
6echo -e  "${COLOR_BOLD_FG_BLUE} Bold   Blue Foreground ${COLOR_RESET}"
7echo -e  "${COLOR_FG_BRIGHT_CYAN} Normal Bright Cyan Foreground ${COLOR_RESET}"
8echo -e  "${COLOR_FG_BRIGHT_RED_BG_BRIGHT_YELLOW} Normal Bright Red Foreground, Bright Yellow Background ${COLOR_RESET}"

We have used Shell variables to make things little more readable.

You can find list of colors with name at this github gist

Testing locally

  1. Download ansi_color_codes.sh

  2. Download ansi_color_codes_usage.sh to the same folder

  3. Run bash ansi_color_codes_usage.sh

    It is recommended to run this on your PC to see which colors suite your liking.

Note: I assume, in case you are planning to change “color” of your shell scripts, you already know the way forward from here!!! Good Luck!!!