Colour output of program run under BASH [closed] Colour output of program run under BASH [closed] linux linux

Colour output of program run under BASH [closed]


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:

Special0  Reset all attributes1  Bright2  Dim4  Underscore   5  Blink7  Reverse8  HiddenForeground colors30  Black31  Red32  Green33  Yellow34  Blue35  Magenta36  Cyan37  WhiteBackground colors40  Black41  Red42  Green43  Yellow44  Blue45  Magenta46  Cyan47  White

So outputting "\033[31;47m" should make the terminal front (text) color red and the background color white.

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";}


Here's a version of the code above from @nightcracker, using stringstream instead of itoa. (This runs using clang++, 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;}