December 21, 2014
Hot Topics:

Linux Console Colors & Other Tricks

  • January 24, 2001
  • By Jay Link
  • Send Email »
  • More Articles »

If you've just begun programming on the Linux console, you may find yourself less than enthused about the available color choices (or lack thereof). Indeed, the default -- dreary gray on black -- brings to mind Henry Ford's famous statement regarding color schemes for his Model T: "You can have any color you want, as long as it's black."

You may have noticed that the "ls" command is capable of producing a rainbow of colors; executables are typically green, compressed files are red, and graphics (.GIF, .JPG, etc.) are purple.

But are these special hues limited to file listings? If not, how can you apply the day-glo treatment to your own code?

The answer is surprisingly simple: all you need are some console escape sequences.

Try typing the following at your command prompt:

   echo -e "\033[35;1m Shocking \033[0m"
What you should have is the word "Shocking" appearing in bright purple. (Sorry, electric pink is not an option).

This is made possible by \033 , the standard console "escape" code, which is equivalent to ^[ , or 0x1B in hex. When this character is received, the Linux console treats the subsequent characters as a series of commands. These commands can do any number of neat tricks, including changing text colors.

Here's the actual syntax:

   \033 [ <command> m
(In practice, you can't have any spaces between the characters; I've just inserted them here for clarity).

Anything following the trailing "m" is considered to be text. It doesn't matter if you leave a space behind the "m" or not.

So this is how you turn your text to a deep forest green:

   echo -e "\033[32mRun, forest green, run."
Note that the "-e" argument to "echo" turns on the processing of backslash-escaped characters; without this, you'd just see the full string of text in gray, command characters and all. Finally, the command "0" turns off any colors or otherwise funkified text:
   \033[0m
Without the "0" command, your output will continue to be processed, like so:
   echo -e "\033[32mThis is green."

   echo "And so is this."

   echo "And this."

   echo -e "\033[0mNow we're back to normal."
Running a command that uses console colors (e.g., ls) will also reset the console to the standard gray on black.

Programming Console Colors

Of course, escape sequences aren't limited to shell scripts and functions. Let's see how the same result can be achieved with C and Perl:
C:
   printf("\033[34mThis is blue.\033[0m\n");

Perl:
   print "\033[34mThis is blue.\033[0m\n";
Trivial, isn't it?





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel