Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

linux - 如何在Linux中更改echo的输出颜色(How to change the output color of echo in Linux)

I am trying to print a text in the terminal using echo command.

(我正在尝试使用echo命令在终端中打印文本。)

I want to print the text in a red color.

(我想用红色打印文本。)

How can I do that?

(我怎样才能做到这一点?)

  ask by satheesh.droid translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use these ANSI escape codes :

(您可以使用以下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
"

which prints love in red.

(用红色印出love 。)

From @james-lim's comment, if you are using the echo command, be sure to use the -e flag to allow backslash escapes .

(根据@ james-lim的注释, 如果使用的是echo命令,请确保使用-e标志以允许反斜杠转义 。)

# Continued from above example
echo -e "I ${RED}love${NC} Stack Overflow"

(don't add "\n" when using echo unless you want to add additional empty line)

((除非要添加其他空行,否则在使用echo时请勿添加"\n" ))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...