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
Color | Code |
---|---|
Black | 0;30 |
Dark Grey | 1;30 |
Red | 0;31 |
Light Red | 1;31 |
Green | 0;32 |
Light Green | 1;32 |
Brown | 0;33 |
Yellow | 1;33 |
Blue | 0;34 |
Light Blue | 1;34 |
Magenta | 0;35 |
Light Magenta | 1;35 |
Cyan | 0;36 |
Light Cyan | 1;36 |
Light Grey | 0;37 |
White | 1;37 |
Background Colors
Color | Code |
---|---|
Black | 40 |
Red | 41 |
Green | 42 |
Yellow | 43 |
Blue | 44 |
Magenta | 45 |
Cyan | 46 |
Light Grey | 47 |
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.