views:

293

answers:

5

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?

+16  A: 

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

Example:

 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.

Thomas
This was the bee's knees on the BBS…
Potatoswatter
+3  A: 

You can use escape sequences, if your terminal supports it. For example:

echo [\033[32m]Hello, [\033[36m]colourful [\033[33mworld!\033[0m]

Vlad
+1  A: 

Feel free to have a look at a code snippet I put here. It's a small tool that colors its output with the help of some macros.

epatel
A: 

The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string

Nick
@Nick it would be a pain to use ncurses to just achieve some coloring via echo. :)
ring bearer
A: 

I wrote a blog post about formatted/colored terminal output and provided a detailed example for use with Ruby, on OS X specifically: http://www.outernet.io/article/347/pretty-terminal-output-in-ruby

Hope you guys don't mind the shameless self promotion.

Mike Keen