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

方法一:ANSI escape

举例:

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

输出:

ANSI escape

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

Foreground colorCodeBackground colorCode
Black0;30Black0;40
Red0;31Red0;41
Green0;32Green0;42
Brown/Orange0;33Brown/Orange0;43
Blue0;34Blue0;44
Purple0;35Purple0;45
Cyan0;36Cyan0;46
Light Gray0;37Light Gray0;47
Dark Gray1;30Dark Gray1;40
Light Red1;31Light Red1;41
Light Green1;32Light Green1;42
Yellow1;33Yellow1;43
Light Blue1;34Light Blue1;44
Light Purple1;35Light Purple1;45
Light Cyan1;36Light Cyan1;46
White1;37White1;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