Conner 的个人资料☆ Conner Wang ☆照片日志列表更多 工具 帮助

日志


7月10日

如何在shell中改变输出字符的颜色

用C或C++:
#include <iostream>
using namespace std;
int main()  
{  
    string beginRed;
    string beginGreen;
    string endColor;
    if(isatty(fileno(stdout)))
    {
        beginRed = "\033[40;31m";
        beginGreen = "\033[40;32m";
        endColor = "\033[0m";
    }
    cout << "TestCase1: " << beginRed << "[OK] " << endColor << endl;
    cout << "TestCase2: " << beginGreen << "[FAILED" << endColor << endl;
    cout << "TestCase3: " << beginRed << "[OK] " << endColor << endl;
    cout << "TestCase4: " << beginGreen << "[FAILED" << endColor << endl;
    return 0;
}

具体颜色代码参见这篇文章:

So You Like Color !!! (The mysterious ^[[ characters)
By Pradeep Padala

The Color Code:     <ESC>[{attr};{fg};{bg}m
I'll explain the escape sequence to produce colors. The sequence to be printed or echoed to the terminal is

    <ESC>[{attr};{fg};{bg}m

The first character is ESC which has to be printed by pressing CTRL+V and then ESC on the Linux console or in xterm, konsole, kvt, etc. ("CTRL+V ESC" is also the way to embed an escape character in a document in vim.) Then {attr}, {fg}, {bg} have to be replaced with the correct value to get the corresponding effect. attr is the attribute like blinking or underlined etc.. fg and bg are foreground and background colors respectively. You don't have to put braces around the number. Just writing the number will suffice.

{attr} is one of following

    0    Reset All Attributes (return to normal mode)
    1    Bright (Usually turns on BOLD)
    2     Dim
    3    Underline
    5    Blink
    7     Reverse
    8    Hidden

{fg} is one of the following
    30    Black
    31    Red
    32    Green
    33    Yellow
    34    Blue
    35    Magenta
    36    Cyan
    37    White

{bg} is one of the following
    40    Black
    41    Red
    42    Green
    43    Yellow
    44    Blue
    45    Magenta
    46    Cyan
    47    White

So to get a blinking line with Blue foreground and Green background, the combination to be used should be
echo "^[[5;34;42mIn color"
which actually is very ugly. :-) Revert back with
echo "^[0;37;40m"