So You Like Color--The Mysterious ^[[ Characters
Have you ever redirected the output of a curses program with colors and wondered what those mysterious ^[[ symbols are? Have you ever tried to produce colors with a printf command without using curses? If the answer to either of these questions is yes, read on. This article attempts to explain the mysterious characters that one finds in the output of a curses program that produces colors. Later, we extend this concept to produce colors with a mere printf command.
In the old days of teletype terminals, terminals were located far away from computers and were connected to them through serial cables. The terminals could be configured by sending a series of bytes to each one. All of the capabilities of terminals could be accessed through these series of bytes, which usually are called escape sequences because they start with an escape (0x1B) character. Even today, with vt100 emulation, we can send escape sequences to the emulator that have the same effect on the terminal window. Hence, in order to print color, we merely echo a control code.
To start, type this on your console:
echo "^[[0;31;40mIn Color"
The first character is an escape character, which looks like two characters, ^ and [. To be able to print this, you have to press CTRL+V and then the ESC key. All the other characters are normal printable characters, so you see the string In Color in red. The type stays that color until you revery back by typing this:
echo "^[[0;37;40m"
As you can see, it is easy to set and reset colors in a console or xterm. A myriad of escape sequences are available with which you can do a lot of things, including moving the cursor and resetting the terminal.
Now, I explain the escape sequence used to produce colors. The sequence to be printed or echoed to the terminal is
<ESC>[{attr};{fg};{bg}m
The first character is ESC, which has to be entered by pressing CTRL+V and then ESC on the Linux console or in xterm, konsole, kvt and so on. Incidentally, CTRL+V ESC also is the combination used to embed an Esc character in a document in Vim. Then, {attr}, {fg} and {bg} have to be replaced with the correct value to achieve the corresponding effect. attr is the attribute, such as blinking or underlined text, while fg and bg are foreground and background colors, respectively. You don't have to put braces around the number; simply writing the number is sufficient.
{attr} needs to be one of the following:
0 Reset All Attributes (return to normal mode)
1 Bright (usually turns on BOLD)
2 Dim
3 Underline
5 Blink
7 Reverse
8 Hidden
{fg} needs to be one of the following:
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
{bg} needs to be one of the following:
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
So, to get a blinking line with a blue foreground and a green background, the combination should be:
echo "^[[5;34;42mIn color"
which actually is very ugly. So, revert back with
echo "^[0;37;40m"
What if you want to use this code color and attribute functionality in a C program? Well, that's simple. Before you printf something, print the escape sequence to produce it in the desired color. I have written a small routine, textcolor(), that does this automatically for you. You can use it in your C programs, along with the #define constants.
|textcolor()|
#include <stdio.h>
#define RESET 0
#define BRIGHT 1
#define DIM 2
#define UNDERLINE 3
#define BLINK 4
#define REVERSE 7
#define HIDDEN 8
#define BLACK 0
#define RED 1
#define GREEN 2
#define YELLOW 3
#define BLUE 4
#define MAGENTA 5
#define CYAN 6
#define WHITE 7
void textcolor(int attr, int fg, int bg);
int main()
{ textcolor(BRIGHT, RED, BLACK);
printf("In color\n");
textcolor(RESET, WHITE, BLACK);
return 0;
}
void textcolor(int attr, int fg, int bg)
{ char command[13];
/* Command is the control command to the terminal */
sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
printf("%s", command);
}
The textcolor() program is modeled against the Turbo C API function. You call the function to set the color and then print it with sprintf(), a function used in Turbo C to produce console output in color.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
7 hours 51 min ago - Dynamic DNS
8 hours 25 min ago - Reply to comment | Linux Journal
9 hours 24 min ago - Reply to comment | Linux Journal
10 hours 14 min ago - Not free anymore
14 hours 16 min ago - Great
18 hours 3 min ago - Reply to comment | Linux Journal
18 hours 11 min ago - Understanding the Linux Kernel
20 hours 26 min ago - General
22 hours 55 min ago - Kernel Problem
1 day 8 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
Bypass the need for CTRL-V ESC
If you want to omit the CTRL-V ESC key sequence you can use \033 instead.
So the lines would read echo "\033[0;31;40m In Color"
and echo "\033[0;37;40m"
This makes it easier to type and to have in scripts.
Excellent post
A fantastic post, I'm just about to do some scripts involving interpreting these colour codes from the logs from the screen utility, this page was invaluable.
Keep up the good work :-)
Cool Tutorial, but...
Cool tutorial, but, I noticed that in the two coding examples you #define BLINK as 4, when it's actually supposed to be '5'
It's just a small type-o, but I thought I'd let you know just incase someone (such as myself) tries to learn from one of the examples without first looking to the list that correctly defines BLINK as 5.
Inspired me to write a library
It's been a slow day before exams started, so I went and wrote a C header I've named SimpleColors after reading this article: CVS (tarball). Great information!
This link is broken!
This link is broken!
awesome
OMG, this is awesome. I've been wondering for about three years how to do colors in c(besides using ncurses). I just happened to be bored and decided to checkout lj's website since I have a subscription and really like the mag.
I think the editors are retarded for not putting this stuff in the magazine. I mean, I have to look at a computer monitor 12 hours a day and I'd really rather go home and read this stuff from the print mag.
But anyway, awsome article Pradeep. Thanks!
bugs in code
In your while loop, the second and third
ifstatements are incorrect. It looks like you copied/pasted the first statement and did not change the conditions -- you are comparingattrwhen it should befgand thenbg.RE: bugs in code
Sorry, forgot to mention that is for the "Demo of Colors" program.
Will Linux make computers soo
Will Linux make computers soon?
http://blog.detectivemarketing.com/2005/10/will-linux-make-computers-soo...
LINUX is no brand
and never will be. So Linux as a organization could not exist. And you cannot build real material things over the web, cause your hands doesnt fit into the cables :)
Re:
In USSR was not any commercical company. But this counrty was better than USA.
Communism rulezzz!
Such a thing could be
Such a thing could be written by the person who never lived in both countries nor US nor USSR. It seems the author of the previous comment is a teen who grown up in Ukraine as an independent country and considers that USSR was a communist state... Funny :)
look it up
Actually the Ukraine beeing a part of the USSR is not that long ago! They became independant 1991.
cool article. i finally under
cool article. i finally understood colors... although a msg about that it is not possible to paste the escape sequence into your terminal would be good.
But what about outputting to a file?
Hi, I use escape sequences in my program but then if I redirect the output to a file, I start seeing all these escape characters in there. Is there a way that I can disable this functionality when outputting to a file?
istty
http://www.thinkage.ca/english/gcos/expl/c/lib/istty.html