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?
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?
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.
You can use escape sequences, if your terminal supports it. For example:
echo [\033[32m]Hello, [\033[36m]colourful [\033[33mworld!\033[0m]
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
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.