Escape sequences
What an escape sequence is and the handful you will see most often.
A control sequence is a short string that starts with the Escape character (ESC, byte 1B, shown as ^[). The terminal does not print it. It acts on it.
The shape
ESC [starts a CSI sequence (control sequence introducer):ESC [ parameters letter.ESC ]starts an OSC (operating system command), ended byBELorESC \.- A few use
ESCplus a single character, such asESC 7(save the cursor) andESC 8(restore it).
Parameters are numbers separated by semicolons. A missing number means 1 or 0.
Control characters
07 BEL beep
08 BS backspace
09 HT tab
0A LF line feed (move down)
0D CR carriage return (to column 1)
1B ESC starts a sequence
A few common CSI sequences
ESC [ n A / B / C / D cursor up / down / right / left by n
ESC [ row ; col H move the cursor
ESC [ 2 J erase the screen
ESC [ K erase to end of line
ESC [ 0 m reset text style and color
ESC [ 1 m bold
ESC [ 31 m red text
ESC [ ? 25 l / h hide / show the cursor
ESC [ c ask the terminal to identify itself
More sequences, including colors and modes, are in the escape sequence table.
Why this matters
- If a terminal shows
^[[31mor[0min the text, the sequence was printed instead of obeyed. Often the output was sent through something that stripped the ESC, or the terminal type was wrong. - If a screen is garbled after a program crashes, the terminal may be stuck in a mode. Type
reset(ortput reset) and pressEnter. ls --colorandgrep --coloronly emit these sequences when the output goes to a terminal.