• 本页内容

46. 为 echo 输出着色


您可以为 echo 语句中使用的文本着色,如下例所示。

$ cat color.sh
# Define the color codes
BLUE="\033[0;34m"
DARK_RED="\033[1;31m"
GREEN="\033[0;32m"
NO_COLOR="\033[0m"
shell="Bash"
echo -e "The best shell is: $shell"
echo -e "The best shell is: $BLUE$shell$NO_COLOR"
echo -e "The best shell is: $DARK_RED$shell$NO_COLOR"
echo -e "The best shell is: $GREEN$shell$NO_COLOR"

使用以下颜色代码表来使用其他颜色。

Color Code
Blank \033[0;30
Red \033[0;31
Green \033[0;32
Brown \033[0;33
Blue \033[0;34
Purple \033[0;35
Cyan \033[0;36
注意:对于深色,将上表中的 [0 替换为 [1。 例如,对于深蓝色,请使用 \033[1;34。 停止后续字符继续使用颜色,使用 \033[0m

除了使用颜色代码之外,您还可以使用 tput 进行其他文本操作。 例如,将文本加粗或加下划线:

$ cat tput.sh
shell="Bash"
echo -e "The best shell is [normal]: $shell"
echo -e "The best shell is [bold]: `tput bold`$shell` tput sgr0`"
echo -e "The best shell is [background]: `tput setb 4`$shell` tput setb 0`"
echo -e "The best shell is [underline]: `tput smul`$shell` tput rmul`"