How To Print With Color In Linux Terminal

The proper (and slower ?) way to do this is using ncurses or similar libraries. Here We’ll talk about a “quick and dirty” method using control characters.

There are special characters, referred to as “control characters“, which, when read by the the console, make it change the way it displays text.

The general format of these control characters is:

ESC[{attr1};…;{attrn}m

Where:

ESC is the escape character. which is “\033” (without the quotes)

[ is a literal opening square bracket

{attr1} is an attribute, which is actually a number with some meaning. Possible values and interpretation are listed below.

m is the literal character m.

You can use as many attributes as you want, separating them by a semicolon (;)

The list of possible attributes:

General Formatting:

0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden

Foreground Colors:

30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White

Background Colors:

40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White

So, for example, If you want to print a red text in bash, what you actually will do is: first switch foreground color to red, print text then reset formatting.

echo -e "\033[31m This text is red \033[0m This text has default color"

In C, you would write it like this:

printf("\033[031m This text is red \033[0m This text has default color\n");

If you want the same but with also a yellow background, you would write:

printf("\033[031;43m This text is red with yellow background \033[0m This text has default color\n");

That’s it. Now you know how to play with colors ;-)

Leave a Reply