ANSI Escape Sequences
Ansi Escape sequences are some standardised byte sequences that make most Terminals do some thing other than just printing characters on screen. Like printing colourful characters!
Using them
The codes can be produced by any string escaping mechanism. In proper programming and scripting languages the syntax for double quotes is usually the same as for printf.
The shell being a bit different you should use either printf
or echo -e
. I have a personal preference for printf
.
Setting Text Color and Effects
I'll focus on Select Graphic Rendition (SGR) codes here, Wikipedia has a more complete list.
_FOOBAR_in bright (
01
) red (31
). After that, it resets to default settings (00
) and prints a newline character (\n
)
# With %s placeholder
As you can see in the example, multiple escape-codes can be chained in one sequence by delimiting them with a ;
.
The \x1b
part is an ASCII escape character it can also be written as \e
, the [
tells the terminal that this is an ANSI Control Sequence Initiator (CSI) after that can come one or more codes. The sequence is finished by an m
to tell the terminal that everything between the CSI and it are SGR codes.
If you are using escape sequences in your scripts: Please make sure that no information gets lost when those sequences are stripped, People with processing pipelines and screenreaders will thank (or at least not curse at) you.
Code | Code to reverse | Effect |
---|---|---|
00 | Reset all effects | |
Foreground color | ||
30-37 | 39 | Set the Foreground color |
90-97 | 39 | Set the Foreground color, bright variation |
Background color | ||
40-37 | 49 | Set the Background color |
100-107 | 49 | Set the Background color, bright variation |
Font effects | ||
01 | 22 | Bright text (usually bold and brighter color) |
02 | 22 | Dim text (usually only effect on color) |
03 | 23 | Italic text |
04 | 24 | Underlined text |
05 | 25 | Blinking text |
07 | 27 | Reverse forground and background color |
Note: The leading zeros are not needed.
Colors
You may have noticed that the 3x
, 4x
, 9x
, and 10x
family of codes all use the last digit in the range from 0 to 7 as a color parameter.
Code | Color |
---|---|
0 | Black or Dark Grey |
1 | Red |
2 | Green |
3 | Yellow |
4 | Blue |
5 | Violet / Purple |
6 | Cyan or Turquoise |
7 | Light Grey or White |
Please keep in mind that diffrent people have diffrent color palettes when you want to write reusable scripts.