如何在 Linux 中更改 echo 的输出颜色
问题描述:
我正在尝试使用 echo 命令在终端中打印文本.
I am trying to print a text in the terminal using echo command.
我想以红色打印文本.我该怎么做?
I want to print the text in a red color. How can I do that?
答
您可以使用这些 ANSI 转义码:
Black 0;30 Dark Gray 1;30
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
Cyan 0;36 Light Cyan 1;36
Light Gray 0;37 White 1;37
然后在脚本中像这样使用它们:
And then use them like this in your script:
# .---------- constant part!
# vvvv vvvv-- the code from above
RED=' 33[0;31m'
NC=' 33[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow
"
用红色打印love
.
来自@james-lim 的评论,如果您使用 echo
命令,请务必使用 -e 标志以允许反斜杠转义.
From @james-lim's comment, if you are using the echo
command, be sure to use the -e flag to allow backslash escapes.
# Continued from above example
echo -e "I ${RED}love${NC} Stack Overflow"
(使用 echo
时不要添加 "
"
除非您想添加额外的空行)
(don't add "
"
when using echo
unless you want to add an additional empty line)