Linux Console Colors & Other Tricks
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:
What you should have is the word "Shocking" appearing in bright purple. (Sorry, electric pink is not an option).
echo -e "\033[35;1m Shocking \033[0m"
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:
(In practice, you can't have any spaces between the characters; I've just inserted them here for clarity).
\033 [ <command> m
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:
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:
echo -e "\033[32mRun, forest green, run."
Without the "0" command, your output will continue to be processed, like so:
Running a command that uses console colors (e.g., ls) will also reset the console to the standard gray on black.
echo -e "\033[32mThis is green."
echo "And so is this."
echo "And this."
echo -e "\033[0mNow we're back to normal."
Programming Console ColorsOf 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";