1. Overview

In this tutorial, we’ll see how we can change colors in a Linux terminal, all right from the command-line.

2. ANSI Escape Codes

ANSI escape codes are standardized commands used to manipulate the behavior and appearance of the text in a terminal or terminal emulator.

The pattern for the color change is “ESC[<foreground_color_code>;<background_color_code>m]”. Let’s write a script that will print red words “Hello world” on a green background using the echo command and then reset colors to normal:

#!/bin/sh
RED_ON_GREEN='\033[31;42m'
RESET='\033[0m'
echo "${RED_ON_GREEN}Hello world${RESET}"

“\033” is the most platform-agnostic way of encoding an ESC character in the terminal, although on Linux, you can also use a reference, “\e”. Plus, it’s worth noting that color settings are not encapsulated in any way.

As a result, if we don’t reset them, they will bleed outside of our script, which is undesirable in most cases.

We can find the full list of color codes on Wikipedia.

3. tput Command

Using ANSI escape codes directly works fine. However, it comes with some downsides. For starters, we use different codes for the same colors for background and foreground. Furthermore, we need to rely on some specific encoding to code an ESC character or use a character reference that may not be portable.

Finally, they are simply less than readable and look a little bit messy.

Fortunately, there’s another option: the tput command. It enables us to query the terminfo database and provides a convenient way to extract escape codes we need.

Let’s recreate the script from the previous section:

#!/bin/sh
RED_FG=`tput setaf 1`
GREEN_BG=`tput setab 2`
RESET=`tput sgr0`
echo "${RED_FG}${GREEN_BG}Hello world${RESET}"

tput setaf” sets foreground color, “tput setab” sets background color, and “tput sgr0” resets all the settings to terminal default. There are 8 standard colors encoded in numbers from 0 to 7 (in order: black, red, green, yellow, blue, magenta, cyan, white).

4. More Than Colors

ANSI escape codes and the tput command alike can be used for much more than changing colors. A full spectrum of their capabilities is far outside of the scope of this article, but we’ll take a look at the styling options that can be useful in everyday scripting.

Let’s write a script that will show a normal text, a bolded text, and an underlined text in the same line in one-second intervals:

#!/bin/sh
MOVE_UP=`tput cuu 1`
CLEAR_LINE=`tput el 1`
BOLD=`tput bold`
UNDERLINE=`tput smul`
RESET=`tput sgr0`
echo "This is normal text"
sleep 1
echo "${MOVE_UP}${CLEAR_LINE}${BOLD}This is bolded"
sleep 1
echo "${MOVE_UP}${CLEAR_LINE}${UNDERLINE}This is underlined${RESET}"

5. Summary

In this article, we learned how to change colors in a Linux terminal with two different methods.

We also showed how they can be used for a more broad cursor and style manipulation.