1. Escape Sequences
Escape Sequences are used to control devices like text terminals, modems, printers.Escape Sequences are an international standard, ISO 6429.
Before this standard emerged, there had been different implementations from different manufactures. At that bad old days, programmers had to write different code for different terminal devices, or use a library like curses to get a portable application.
Since ISO 6429 appeared, all terminal devices have been designed to follow this standard. But different products still have their own extensions beyond the standard. As a result, libraries like Ncurses are stilled needed for UI programs (like vim, Emacs) targeted to run on a wide range of platforms. But for simple applications, ISO 6429 is enough.
e.g.
ESC N # Select Shift Two for character set
ESC O # Select Shift Three for character set
ESC P # Device Control String
ESC [ # Control Sequence Introducer (CSI)
ESC \ # String terminator
ESC X # Start of string
The most useful one is "ESC [", which is named Control Sequence Introducer.
2 Control Sequences
A Control Sequence is an Escape Sequence followed by [.
A Control Sequence has a defined format as below.
ESC [ parameters final-byte
The final-byte is used to group different functions. e.g.
ESC [ n A # Move the cursor n characters up
ESC [ n B # Move the cursor n characters down
ESC [ n C # Move the cursor n characters forward
ESC [ n D # Move the cursor n characters backward
ESC [ n K # Erase n characters
ESC [ n m # Select Graphic Rendition (SGR)
3. SGR
An SGR is a special case of Control sequence used for changing what the characters look like on a terminal.
ESC [ n m # Select Graphic Rendition (SGR)
e.g.
ESC [ 0 m # Reset to the default states
ESC [ 1 m # Bold
ESC [ 2 m # Faint
ESC [ 3 m # Italic
ESC [ 4 m # Underline
...
ESC [ 31 m # Set the foreground color to red
ESC [ 41 m # Set the background color to red
...
n=[30,37] is used for setting foreground-color
n=[40,47] is used for setting background-color
There are 8 colors in order, Black, Red, Green, Yellow, Blue, Purple, Cyan, White.
Different parameters can be combined together in on SGR, e.g.
ESC [ 1 ; 31 m # Bold and Red
4. Example: print 8 different colored text
$ cat sgr.sh
#!/bin/bash
# print 8 colors
for color in {30..37}
do
# set foreground color
echo -ne "\x1b["
echo -n $color
echo -n "m"
# print the text
echo Hello, SGR
# reset to default
echo -ne '\x1b[0m'
done
Note: there are two common ways to input ESC in a script
- Input by keyboard: Ctr + v + ESC, it looks like ^[.
- Use backslash: echo -e '\x1b'.
I used the latter in the example script.
The screenshot is as below.
Please note that the first line is invisible as its foreground color is black, the same as the background.
No comments:
Post a Comment