Using Colors in Terminal Output
ANSI escape sequences is a standard to control cursor location, color, font styling, and other options on terminal emulators.
The sequences are grouped by their sequence type. CSI (Control Sequence Introducer) is one of the groups, their sequence starting with ESC [
. SGR (Select Graphic Rendition) is a part of CSI, it sets display attributes.
The form of SGR:
ESC [ n m
# In terminal, we can write
\e[nm
# or
\x1b[nm
ESC
is a character in the ASCII table.
n
consists of one or more decimal digits, separated by ;
.
The sequence ends with m
.
Sequence | Description |
---|---|
ESC [ 30…37 m | Set ANSI text color |
ESC [ 38 ; 5 ; n m | Set text color, 256-color, n is color index from 0 to 255 |
ESC [ 38 ; 2 ; r ; g ; b m | Set text color, 24-bit true color, r, g, b are from 0 to 255 |
ESC [ 39 m | Reset text color to default |
ESC [ 40…47 m | Set ANSI background color |
ESC [ 48 ; 5 ; n m | Set background color, 256-color, n is color index from 0 to 255 |
ESC [ 48 ; 2 ; r ; g ; b m | Set background color, 24-bit true color, r, g, b are from 0 to 255 |
ESC [ 49 m | Reset background color to default |
ESC [ 90…97 m | Set bright ANSI text color |
ESC [ 100…107 m | Set bright ANSI background color |
ESC [ 1 m | Bold |
ESC [ 0 m | Reset |
ANSI colors:
Text Color | Background Color | Color Name |
---|---|---|
30 | 40 | black |
31 | 41 | red |
32 | 42 | green |
33 | 43 | yellow |
34 | 44 | blue |
35 | 45 | magenta |
36 | 46 | cyan |
37 | 47 | white |
# red A
echo '\e[31mA'
# white A, red background
echo '\e[37;41mA'
# bright and bold A, red background
echo '\e[1;97;41mA'
# red A, green B
echo '\e[31mA\e[0B\e[32mB'
To print 256 text and background colors:
#!/usr/bin/env python3
# text colors
for i in range(0, 16):
for j in range(0, 16):
code = str(i * 16 + j)
print(f"\x1b[38;5;{code}m{code.ljust(4)}", end=' ')
print("\x1b[0m")
# background colors
for i in range(0, 16):
for j in range(0, 16):
code = str(i * 16 + j)
print(f"\x1b[48;5;{code}m{code.ljust(4)}", end=' ')
print("\x1b[0m")
Discovering Recently Installed Commands In Zsh
When using Zsh (with Oh My ZSH), the newly installed commands will not be automatically completed without opening new terminal tab or window. We can run the command to fix it:
rehash
# or
hash -rf