You’ve probably notices that some commands can output colorful text in the terminal. Here is how to do it yourself.

Here is a teaser.

echo -e "\e[32mHello World\e[0m"

Background

It gets a bit technical.

The -e flag makes echo interpret backslash escapes. With it we can type in \ followed by a character code to output none-printable characters.

You see, terminals are based on the ASCII standard for encoding character. Each symbol shown on the screen needs to be encoded in binary somehow. ASCII is just a way to encode those.

ASCII table shows how characters are encoded.

Instead of writing long sequences like “00001010” for “a” it is common to use either decimal (0-255), hex (00-ff) or octal (000-377) to represent a byte. Btw ASCII only uses 7-bits, so the last bit have been used for various extensions including UTF-8.

The letter “a” has the character code 61 in hex or 141 in octal. It can be printed using a backslash sequence:

# hex
echo -e "\x61"

# octal
echo -e "\0141"

Not terrible exiting, but it illustrates the idea.

To do something a bit more fun, we can try to ring the terminal bell. It will either make a sound or give a visual clue depending on your terminal emulator.

echo -e "\x07"

If we echo the character code for escape, then we can use a special sequence to control how the terminal prints characters.

echo -e "\033[1mHello World"

Where “\033” is escape and “[1m” is a control code to make text bold.

Because “\033” is annoying to remember, there is also the shortcut “\e”.

Fun stuff

Note: support depends on your terminal.

To set foreground color to red:

echo -e "\e[31mRed"

To set background color to red:

echo -e "\e[41mRed"

Here is a table of the standard colors.

ColorForegroundBackground
Black3040
Red3141
Green3242
Yellow3333
Blue3444
Magenta3545
Cyan3646
Gray3747

Depending on your terminal, it might also be possible to go full RGB mode.

echo -e "\e[38;2;255;192;203mPink"

RGB color (255, 192, 203) for pink.

We can also change the text in various other ways. Here are some examples:

echo -e "\e[1m Bold"
echo -e "\e[3m Italic"
echo -e "\e[4m Underline"
echo -e "\e[5m Slow blink"
echo -e "\e[6m Fast blink"

Last, use “\e[0m” to reset.

echo -e "\e[32mColor \e[0mReset"

See full list