ANSI Escape Code#
ANSI Escape Code is a technique used to control cussor location, color, font styling on a text terminals, aka “command line” or “cmdline” or “cli”.
In HTML world, all these can be done easily. In other environment, it may not be as simple as in HTML world.
Below are the examples, from Wikipedia, how it can be used to change the display on the terminal emulator.
ANSI Color Code#
Foreground | Background | Color Name | VGA |
---|---|---|---|
30 | 40 | Black | 0,0,0 |
31 | 41 | Red | 170,0,0 |
32 | 42 | Green | 0,170,0 |
33 | 43 | Yellow | 170,85,0 |
34 | 44 | Blue | 0,0,170 |
35 | 45 | Magenta | 170,0,170 |
36 | 46 | Cyan | 0,170,170 |
37 | 47 | White | 170,170,170 |
90 | 100 | Bright Black | 85,85,85 |
91 | 101 | Bright Red | 255,85,85 |
92 | 102 | Bright Green | 85,255,85 |
93 | 103 | Bright Yellow | 255,255,85 |
94 | 104 | Bright Blue | 85,85,255 |
95 | 105 | Bright Magenta | 255,85,255 |
96 | 106 | Bright Cyan | 85,255,255 |
97 | 107 | Bright White | 255,255,255 |
Bash (color codes)#
Use the following template to print color text.
echo -e "\e[COLORmSample Text\e[0m"
echo -e "\e[COLOR1;COLOR2mSample Text\e[0m"
echo -e "\e[MODE;COLOR1;COLOR2mSample Text\e[0m"
Options | Description |
---|---|
echo -e | Interpre blackslash escape |
\e[ | Begin escape color change |
MODE | Color mode |
COLOR1m | Color code + ’m' |
COLOR2m | Color code + ’m' |
\e[0m | Reset |
Mode | Description |
---|---|
0 | Normal character |
1 | Bold character |
4 | Underlined character |
5 | Blink character |
7 | Reverse video character |
Example#
Simple test.
$ echo -e "\e[37m White_Text \e[0m"
White_Text
$ echo -e "\e[1;34m Light_Blue_Text \e[0m"
Light_Blue_Text
$ echo -e "\e[1;33;4;44m Underlined Yellow on Blue \e[0m"
Underlined Tellow on Blue
Test all colors with a for-loop.
for code in {0..255}
do echo -e "\e[38;5;${code}m"'\\e[38;5;'"$code"m"\e[0m"
done
Bash (flasher)#
The following Bash function flashes the terminal until the user presses a key.
flasher () { while true; do printf \\e[?5h; sleep 0.1; printf \\e[?5l; read -s -n1 -t1 && break; done; }
Or, you can add it to shell script file.
#!/bin/bash
flasher () {
while true
do
printf \\e[?5h
sleep 0.1
printf \\e[?5l
read -s -n1 -t1 && break
done
}
PowerShell#
Testing color with ANSI Escape code in PowerShell.
PS> $esc = [char]27
PS> write-host "$esc[32m Green $esc[0m"
Green
PS>
Links#
- Wikipedia ANSI escape code
- VT100 User Guide
- Tool: ANSI