节目的彩色输出下运行BASH [英] Colour output of program run under BASH
问题描述
我需要能够能够使终端上的一些文字更明显,而且我认为是做彩色文本。无论是实际的文本,或每个字母的矩形啄(思考一下vi的光标)的空间。我认为是我的应用程序唯一重要的两个额外的规格是:程序应该是发行无关(是板上钉钉的事情是,code将只在BASH运行),它不应该写作时输出多余的字符到一个文件中(无论是从实际code或管道输出时)
I need to be able to be able to make some text on terminal more noticeable, and what I thought was to make the text colored. Either the actual text, or the space in each letter's rectangle-thingy (think vi's cursor). The only two extra specs that I think are important for my application are : the program should be distro-independent (a certainty is that the code will only be run under BASH), and it shouldn't output extra characters when writing to a file (either from the actual code, or when piping the output)
我搜索了一些信息网页,但我只找到去precated cstdlib(stdlib.h中)的信息,我需要(实际上,它更多的是希望),用做iostream的功能。
I searched the web for some info, but I could only find info for the deprecated cstdlib (stdlib.h), and I need (actually, it's more of a "want") to do it using the functionality of iostream.
推荐答案
大多数终端尊重ASCII颜色序列。他们通过输出 ESC
,后跟 [
,则颜色值的分号分隔的列表,那么<$ C工作$ C> M 。这些都是常见的值:
Most terminals respect the ASCII color sequences. They work by outputting ESC
, followed by [
, then a semicolon-separated list of color values, then m
. These are common values:
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;47米
应使终端前(文本)红色和背景颜色白色
So outputting "\033[31;47m"
should make the terminal front (text) color red and the background color white.
您可以在C ++的形式很好地把它包起来:
You can wrap it nicely in a C++ form:
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";
}
这篇关于节目的彩色输出下运行BASH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!