Bash Bits: Add colour output to your script

18-09-2013 | Remy van Elst

Table of Contents

Bash Bits are small examples and tips for Bash Scripts. This bash bit shows you how to add coloured output to your scripts.

All Bash Bits can be found using this link

A little background first on how this all works. Coloured output has to be supported by your terminal emulator, but most modern ones support it. It works by sending specific control codes to your terminal.

Terminal (control-)codes are needed to give specific commands to your terminal. A terminal control code is a special sequence of characters that is printed (like any other text). If the terminal understands the code, it won't display the character-sequence, but will perform some action. You can always print the codes with a simple echo command.

Because there's a large number of different terminal control languages, usually a system has an intermediate-layer to talk to it. The real codes are looked up in a database for the currently detected terminal type and you give standardized requests to an API or (from the shell) to a command.

One of these commands is tput - it accepts a set of acronymes and parameters for them, looks up the correct codes for the detected terminal in the terminfo database and prints the correct codes (the terminal hopefully understands).

You can read more about terminal control codes and tput in the terminfo(5) manual page, click this link for the online version

When I need to use colours in my scripts I often just use red and green. I have a set of functions which I use named after the colour:

black() { echo "$(tput setaf 0)$*$(tput setaf 9)"; }
red() { echo "$(tput setaf 1)$*$(tput setaf 9)"; }
green() { echo "$(tput setaf 2)$*$(tput setaf 9)"; }
yellow() { echo "$(tput setaf 3)$*$(tput setaf 9)"; }
blue() { echo "$(tput setaf 4)$*$(tput setaf 9)"; }
magenta() { echo "$(tput setaf 5)$*$(tput setaf 9)"; }
cyan() { echo "$(tput setaf 6)$*$(tput setaf 9)"; }
white() { echo "$(tput setaf 7)$*$(tput setaf 9)"; }

Then when I need to colourize some output I can just use the function like so: red "Error: Something went horribly wrong...". Down below you can find sample code which should print text in all the above defined colours:

black "This is black text"
red "This is red text"
green "This is green text"
yellow "This is yellow text"
blue "This is blue text"
magenta "This is magenta text"
cyan "This is cyan text"
white "This is white text"

This image shows you how it looks on my terminal:
Terminal Colours

And last but not least here is a bash command which prints out all colour that your terminal supports. Good to test if you have 256 colours enabled or not, plus it shows you the number to use with tput for that colour.

( x=`tput op` y=`printf %$((${COLUMNS}-6))s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done; )

Tags: ansii, bash, bash-bits, color, colour, shell, tput,