Printing with Color to a Linux Console

A few days ago, I wanted to print colored strings from C++ to Linux terminal. I made a small research in the web and found a simple way to do this.

It’s possible to format the foreground color, background color and other display settings by printing a certain string to your terminal. This feature is implemented in the terminal itself, and is not programming language dependent.

The magic string is of this format:

ESC[{attr1};…;{attrn}m

where:

ESC is the escape character. (see examples below).

{attr1} to {attrn} are the attributes you’re welling to set. Should be of the following values:

0	Reset all attributes
1	Bright
2	Dim
4	Underscore
5	Blink
7	Reverse
8	Hidden

	Foreground Colors
30	Black
31	Red
32	Green
33	Yellow
34	Blue
35	Magenta
36	Cyan
37	White

	Background Colors
40	Black
41	Red
42	Green
43	Yellow
44	Blue
45	Magenta
46	Cyan
47	White


For example, to change the text color in your terminal into red, type the following command (in terminal):

1
echo -e "\e[31mThis Text in Red"

The “-e” flag tells echo to enable interpretation of backslash escapes (according to echo’s manpage)

The “\e” is the escape character.

31 is for red foreground.


Another example, this time with C++, which should produce a green text over a black background:

1
cout << "\033[32;40m" << "Green fore over Black back" << endl;


To do the same with C, your code should look like this:

1
printf("\033[32;40mGreen fore over Black back");


And with Python:

1
print "\033[32;40mGreen fore over Black back"


Credits:

ANSI/VT100 Terminal Control Escape Sequences

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

No related posts.

Tags: , ,

Thursday, August 7th, 2008 Linux

3 Comments to Printing with Color to a Linux Console

  • Ali Ayoub says:

    Great job!
    Thanks for sharing

  • awhan patnaik says:

    thanks that was really helpful :D

  • Leave a Reply

    my email
    my photo
    Hi,
    My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and a BSc. in electrical engineering from The Electrical Engineering school , Technion , Israel.
    I'm a Verification Engineer in Mellanox Technologies Ltd.
    I love Linux, the Command Line and the OpenSource Community.
    I used to write Poems (Arabic) when I was able to find time for this.
    August 2008
    S M T W T F S
    « Jul   Oct »
     12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31  
    SEO Powered by Platinum SEO from Techblissonline

    Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.