Macha Macha - 1 year ago 89
Linux Question

How do I output coloured text to a Linux terminal?

How do I print coloured characters to a Linux terminal that supports it? I'm using C++ for this program, but I think that might be irrelevant.

EDIT: And secondly, how do I tell if it supports colour codes?

Answer Source

You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.


 cout << "\033[1;31mbold red text\033[0m\n";

Here, \033 is the ESC character, ASCII 27. It is followed by [, then one or two numbers separated by ;, and finally the letter m. See the table on Wikipedia for the meaning of the numbers.

Edit: To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download