Weekly - issue 45

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.

SequenceDescription
ESC [ 30…37 mSet ANSI text color
ESC [ 38 ; 5 ; n mSet text color, 256-color, n is color index from 0 to 255
ESC [ 38 ; 2 ; r ; g ; b mSet text color, 24-bit true color, r, g, b are from 0 to 255
ESC [ 39 mReset text color to default
ESC [ 40…47 mSet ANSI background color
ESC [ 48 ; 5 ; n mSet background color, 256-color, n is color index from 0 to 255
ESC [ 48 ; 2 ; r ; g ; b mSet background color, 24-bit true color, r, g, b are from 0 to 255
ESC [ 49 mReset background color to default
ESC [ 90…97 mSet bright ANSI text color
ESC [ 100…107 mSet bright ANSI background color
ESC [ 1 mBold
ESC [ 0 mReset

ANSI colors:

Text ColorBackground ColorColor Name
3040black
3141red
3242green
3343yellow
3444blue
3545magenta
3646cyan
3747white
# 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