Nothing spruces up command-line output the way colors do. Just like when you’re customizing your [Bash] prompt, you can use color codes in strings to colorize your output. Keep in mind, these colors will only work on the command-line and not in a browser. First let’s take a look at the syntax:

echo "\e[0;31;42mMerry Christmas!\e[0m\n";

The above command will echo out “Merry Christmas!” in a red font with a green background. The first part of the string, \e is the escape character and could alternatively be represented by \033 in octal or using the function call chr(27) if you want to close and reopen the string a bunch of times.

Next up is [0;31;42m, this is what sets the foreground color (0;31) and the background (42). This is all followed up by the text we’re colorizing. After that is another color declaration that will reset the color to the terminal’s default colors (usually grey text on a black background).

So now that we know how to colorize text, let’s take a look at all of the colors that are available. All in there are 16 different foregrounds and 8 backgrounds. Of the foregrounds, they are split between a normal colors and lighter alternate versions that actually end up being displayed differently depending on the terminal being used. Sometimes they are heavier text, sometimes alternative colors. The colors and codes are as follows:

Foreground Colors

ColorCode
Black0;30
Dark Grey1;30
Red0;31
Light Red1;31
Green0;32
Light Green1;32
Brown0;33
Yellow1;33
Blue0;34
Light Blue1;34
Magenta0;35
Light Magenta1;35
Cyan0;36
Light Cyan1;36
Light Grey0;37
White1;37

Background Colors

ColorCode
Black40
Red41
Green42
Yellow43
Blue44
Magenta45
Cyan46
Light Grey47

It’s worth noting that you actually don’t need to set both the foreground and the background color, if you wanted to you could simply set one or the other using the aforementioned codes. When defining both, you must specify the foreground color first and just separate the codes with a semi-colon.





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: