认识
文档:Standard:ECMA-48,ISO/IEC 6429,FIPS 86,ANSI X3.64,JIS X 0211
ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. 简而言之,ANSI Escape Code 是个字符序列,其用于控制终端来操纵终端文字的显示行为。
ANSI American National Standards Institute
History https://en.wikipedia.org/wiki/ANSI_escape_code#History
组成
Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text.
性质
提供终端字体颜色修改 Color
https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
提供光标位置控制功能 Cursor Location
移动光标的转义序列 | Cursor Movement | https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html
- Position the Cursor:
\033[<L>;<C>H
Or
\033[<L>;<C>f
puts the cursor at line L and column C.
- Move the cursor up N lines:
\033[<N>A
- Move the cursor down N lines:
\033[<N>B
- Move the cursor forward N columns:
\033[<N>C
- Move the cursor backward N columns:
\033[<N>D
- Clear the screen, move to (0,0):
\033[2J
- Erase to end of line:
\033[K
- Save cursor position:
\033[s
- Restore cursor position:
\033[u
构建
The entire table of ANSI color codes.https://github.com/termstandard/colors
ANSI Color Code | https://github.com/termstandard/colors
\e[31m \033[31m
\e[0m \033[0m
应用
场景 | 实现进度条
#!/bin/bash
echo -n '------------------------------------------'
echo -n -e "\r" # 移动光标到行首
while true;
do
echo -n -e '\033[1C' # 光标向后移动一位
echo -n -e '\b' # 删簇一个字符
echo -n '#' # 打印一个井号
sleep 0.5 # 休眠 500ms
done
场景 | 删除颜色代码
./somescript | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g'
参考
Wikipedia/ANSI escape code
Bash tips: Colors and formatting (ANSI/VT100 Control sequences)