Colorful Print to Terminal

This post introduces how to use escape code to get colorful output in a terminal.

Many terminals follow the ANSI escape code format and support colorful outputs. Here is an example string that would be displayed with colors:

"\033[32mred\033[1;32mGREEN\033[21;34mblue"

As we can see, it begins with \033, the ASCII code 27 ESC. It is followd by [ and some numbers to indicate the colors. Eventually, we terminate the escape code by m. Here comes the table for colors’ numbers:

Color Foreground Background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
light grey 37 47
dark grey 90 100
light red 91 101
light green 92 102
light yellow 93 103
light blue 94 104
light magenta 95 105
light cyan 96 106
white 97 107

And here comes the table for special font settings:

Settings on off
reset 0  
bold/bright 1 21
dim 2 22
underline 4 24
blink 5 25
inverse 7 27
hidden 8 28
strikeout 9 29

The color and font settings would take effect as long as you output it to terminal, not matter in which way you do the output. Examples are:

  • echo: echo -e "\033[1;91mHello red
  • c++: cout << "\033[4;92mHello green";
  • python: print("\033[9;94mHello blue")

Credits