在 bash 中获取颜色输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2437976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get color output in bash
提问by Open the way
when compiling some projects on linux terminal, I get usually a long output consisting of a lot of information. Usually this information is MONOCHROME. I wonder if bash can be modified somehow, so in all outputs or in some specific outputs (like from Makefile, etc) I can get different colors dependeing on, for instance:
在 linux 终端上编译一些项目时,我通常会得到一个包含大量信息的长输出。通常此信息是单色的。我想知道 bash 是否可以以某种方式进行修改,因此在所有输出或某些特定输出(如来自 Makefile 等)中,我可以获得不同的颜色,例如:
make[1]: Leaving directory
or
或者
g++ -DHAVE_CONFIG_H -I.
etc.
等等。
Thanks
谢谢
采纳答案by Jeff Walden
Sure, just use Bash functions, like, say this one:
当然,只需使用 Bash 函数,比如,说这个:
make()
{
pathpat="(/[^/]*)+:[0-9]+"
ccred=$(echo -e "3[0;31m")
ccyellow=$(echo -e "3[0;33m")
ccend=$(echo -e "3[0m")
/usr/bin/make "$@" 2>&1 | sed -E -e "/[Ee]rror[: ]/ s%$pathpat%$ccred&$ccend%g" -e "/[Ww]arning[: ]/ s%$pathpat%$ccyellow&$ccend%g"
return ${PIPESTATUS[0]}
}
(Originally via Highlight Warnings in Make.)
(最初通过Make 中的突出显示警告。)
回答by Fabio
I found that in bash tput setfdoesn't work. I found this commands for bash that are working well
我发现在 bashtput setf中不起作用。我发现这个 bash 命令运行良好
handy tput commands
tput bold - Bold effect
tput rev - Display inverse colors
tput sgr0 - Reset everything
tput setaf {CODE}- Set foreground color, see color {CODE} below
tput setab {CODE}- Set background color, see color {CODE} below
Colors {code} code for tput command
Color {code} Color
0 Black
1 Red
2 Green
3 Yellow
4 Blue
5 Magenta
6 Cyan
7 White
回答by Norman Ramsey
You can do this portably by using the tputcommand and the terminfo(5)database.
For example,
您可以通过使用tput命令和terminfo(5)数据库来便携地执行此操作。例如,
tput setf 5
with terminal as standard out, will set the foreground color to purple (or something like it; I'm color blind). tput setf 0resets the foreground color to the default.
将终端作为标准输出,将前景色设置为紫色(或类似的颜色;我是色盲)。 tput setf 0将前景色重置为默认值。
For more information, look up terminfo.
有关更多信息,请查找terminfo。
回答by Dorku
回答by mmaruska
It seem more like you want the colorized output from make(1). In that case, I'd recommend patches for gnu make from http://git.goodpoint.de/?p=make.git;a=shortlog;h=refs/heads/color-v5.1described on the ML: http://old.nabble.com/-rfc--Colorized-output-for-GNU-make--td32547742.html
看起来更像是您想要 make(1) 的彩色输出。在这种情况下,我会推荐 ML 中描述的http://git.goodpoint.de/?p=make.git;a=shortlog;h=refs/heads/color-v5.1中的gnu make 补丁 :http://old.nabble.com/-rfc--Colorized-output-for-GNU-make--td32547742.html

