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
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!No related posts.
3 Comments to Printing with Color to a Linux Console
Leave a Reply
About Me
Tags
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- iPhone
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Regular Expressions
- Science
- Security
- Shell Scripts
- Short Posts
- Social Networks
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- July 2010 (5)
- June 2010 (1)
- May 2010 (1)
- April 2010 (3)
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (2)

Great job!
Thanks for sharing
thanks that was really helpful
Happy to help