Shell 脚本彩色输出

/

在 Shell 脚本中,为了强调,经常会用到彩色输出。

方法一:ANSI escape

举例:

echo -e "\033[0;31mRed text \033[0;31;47mand white background\033[0m"

输出:

ANSI escape

色彩和 ANSI escape code 的对应关系:

Foreground color Code Background color Code
Black 0;30 Black 0;40
Red 0;31 Red 0;41
Green 0;32 Green 0;42
Brown/Orange 0;33 Brown/Orange 0;43
Blue 0;34 Blue 0;44
Purple 0;35 Purple 0;45
Cyan 0;36 Cyan 0;46
Light Gray 0;37 Light Gray 0;47
Dark Gray 1;30 Dark Gray 1;40
Light Red 1;31 Light Red 1;41
Light Green 1;32 Light Green 1;42
Yellow 1;33 Yellow 1;43
Light Blue 1;34 Light Blue 1;44
Light Purple 1;35 Light Purple 1;45
Light Cyan 1;36 Light Cyan 1;46
White 1;37 White 1;47

方法二:tput

举例:

echo "$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)"

输出:

tput

前景色、背景色设置:

tput setab [1-7] # Set the background color using ANSI escape
tput setaf [1-7] # Set the foreground color using ANSI escape

色彩、编号对应关系:

Num Color #define R G B
0 black COLOR_BLACK 0,0,0
1 red COLOR_RED 1,0,0
2 green COLOR_GREEN 0,1,0
3 yellow COLOR_YELLOW 1,1,0
4 blue COLOR_BLUE 0,0,1
5 magenta COLOR_MAGENTA 1,0,1
6 cyan COLOR_CYAN 0,1,1
7 white COLOR_WHITE 1,1,1

文本设置:

tput bold    # Select bold mode
tput dim     # Select dim (half-bright) mode
tput smul    # Enable underline mode
tput rmul    # Disable underline mode
tput rev     # Turn on reverse video mode
tput smso    # Enter standout (bold) mode
tput rmso    # Exit standout mode

其他设置:

tput sgr0    # Reset text format to the terminal's default
tput bel     # Play a bell

参考:http://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux

Comments