在BASH下运行程序的颜色输出

我需要能够使terminal上的一些文本更加明显,而我认为是使文本变成彩色的。 无论是实际的文本,还是每个字母的矩形空间(想想vi的光标)。 我认为对于我的应用程序唯一的两个额外的规格是重要的:程序应该是发行版独立的(确定的是,代码将只在BASH下运行),并且当写入文件时它不应该输出额外的字符(来自实际的代码,或者pipe道输出)

我在网上search了一些信息,但是我只能find不赞成使用的cstdlib(stdlib.h)的信息,我需要(实际上,它更像是一个“想要”)使用iostream的function来完成。

大多数终端都遵守ASCII颜色序列。 他们通过输出ESC工作,然后是[ ,然后是以分号分隔的颜色值列表,然后是m 。 这些是共同的价值观:

 Special 0 Reset all attributes 1 Bright 2 Dim 4 Underscore 5 Blink 7 Reverse 8 Hidden Foreground colors 30 Black 31 Red 32 Green 33 Yellow 34 Blue 35 Magenta 36 Cyan 37 White Background colors 40 Black 41 Red 42 Green 43 Yellow 44 Blue 45 Magenta 46 Cyan 47 White 

因此,输出"\033[31;47m"应使终端前(文本)颜色为红色,背景颜色为白色。

你可以用C ++格式很好地包装它:

 enum Color { NONE = 0, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE } std::string set_color(Color foreground = 0, Color background = 0) { char num_s[3]; std::string s = "\033["; if (!foreground && ! background) s += "0"; // reset colors if no params if (foreground) { itoa(29 + foreground, num_s, 10); s += num_s; if (background) s += ";"; } if (background) { itoa(39 + background, num_s, 10); s += num_s; } return s + "m"; } 

以上是来自@nightcracker的代码版本,使用stringstream代替itoa 。 (这运行使用铿锵++,C + + 11,OS X 10.7,iTerm2,bash)

 #include <iostream> #include <string> #include <sstream> enum Color { NONE = 0, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; static std::string set_color(Color foreground = NONE, Color background = NONE) { std::stringstream s; s << "\033["; if (!foreground && ! background){ s << "0"; // reset colors if no params } if (foreground) { s << 29 + foreground; if (background) s << ";"; } if (background) { s << 39 + background; } s << "m"; return s.str(); } int main(int agrc, char* argv[]) { std::cout << "These words should be colored [ " << set_color(RED) << "red " << set_color(GREEN) << "green " << set_color(BLUE) << "blue" << set_color() << " ]" << std::endl; return EXIT_SUCCESS; } 

你可能想看看VT100的控制代码 。

你也可以自定义功能,如:

 void textcolor(int color) { std::cout<<"\033]"<<color; } 

欲了解更多信息,请阅读http://en.wikipedia.org/wiki/ANSI_escape_code