Please enable JavaScript to use CodeHS

ANSI Colors

Understanding ANSI colors in the terminal

By Andy Bayer

Software Developer at CodeHS

Every ANSI sequence is going to begin with the escape code, a sequence indicating to the terminal that the next characters it receives are going to be an ANSI code.

In the tutorial for clearing the console with ANSI sequences, we saw the escape code is \x1b, \033, or \u001b, depending on if you’re using hexadecimal, octal, or unicode. For simplicity, let’s use \x1bc, the hexadecimal respresentation. And to make it even easier, let’s put that value in a variable named ESC:

Just like we use the code [2J to clear the console, we can use special codes to change the color of text.

The ANSI codes for color work as follows:

Code Color
[30m Black Text
[31m Red Text
[32m Green Text
[33m Yellow Text
[34m Blue Text
[35m Purple Text
[36m Cyan Text
[37m White Text

Putting a color code after the escape code will change the color of your text.
Let’s try that in an example:

You can even combine ANSI colors in the same string. Let’s make a rainbow of dots!

Awesome!
However, our “Cool!!!” is in purple.
That’s because the colors need to be terminated. To terminate a color, use the code [0m. Try putting a \x1b[0m after the purple dot, or before “Cool!!!” to terminate the color.

The background color of a letter can be changed, too!
The colors have the exact same numerals, but instead of using [3, we’ll use [4.

For example, a red letter is [31m, so a red background is [41m.
Another example!

You can see we set the foreground color to white once, then changed only the background color throughout.

There’s even more you can do with colors!
The terminal in CodeHS supports “bright” versions of colors, which can be accessed by adding ;1m after any color.

You can also bold and underline text, using [1m for bold, [4m for underline, and [7m for “inverse” text (switch foreground and background colors).

Here’s an example of a program using ANSI sequences to move the cursor to create a loading bar in place: