Thursday, September 8, 2016

Coloring Terminal Text with ANSI Escape Sequences

If you have ever wondered how to print colored text to the command line, this is the post for you!

Pretty much all newer computers (including Windows 10 and above) allow for the use of ANSI escape sequences. ANSI escape codes are a holdover from the 1980's, but no one has come up with a better standardized way of modifying command line output, so they've stuck around long enough that even Windows has incorporated them. (Anyone, who is old enough to have dealt with IE6 gets that joke.)

Try typing the following into a terminal window.

printf "I'm \033[0;31mRED\033[0m"

You should see "I'm RED" printed to your window. Now wasn't that simple?

You can do a lot more with ANSI escape codes than just change colors on the terminal. If you've ever seen a terminal based application with windows, subwindows, scrolling and all that cool Text User Interface (TUI) stuff. You can do that with ANSI escape codes.

The next important question to ask is, How did the ANSI escape code do that?

First you need to understand the anatomy of ANSI escape sequences. When dealing with colors, the format is

<ESC>[<code>m

The <ESC> was the \033 in our printf example, but might be something else depending on your system or preference. For instance, \u001B is commonly used when including ANSI escape sequences from programming languages like Java's print() method.

The <code> can be any valid text related code. If you include multiple codes, separate them with a semicolon. If you're very observant, you've probably already discovered that the initial ANSI escape sequence used above has two codes—0 and 31.

Finally you end with an 'm'. The letter might be different for some of the other types of ANSI control codes, but for text manipulation, it is typically an 'm'.

There are tons of ANSI control codes to play with. Here's a short list of the common ones used for manipulating text.

Text attributes
0 All attributes off (reset)
1 Bold on
4 Underscore (on monochrome display adapter only)
5 Blink on
7 Reverse video on
8 Concealed on

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

Background colors (great for colored spaces)
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White


Always remember to undo any changes with

<ESC>[0m

That resets the output to it's default state. In other words, it turns all attributes off. In out example above, we used "\033[0m".

No comments:

Post a Comment