Your requirement
You want to produce coloured text output in your shell scripts. You have already seen this in various places (e.g. when starting the services at boot time) and have wondered how it is done.
The principle behind it
All terminal emulations common under Linux (e.g. xterm, konsole, the Linux console, PuTTY) support certain control characters that can be used to influence text attributes. You simply have to output these with echo
.
How it works in detail
All control sequences are initiated with Escape
[. After that comes a number, and then a lowercase m
. The escape character has the Asciicode 27. To output this with echo
, you need to use the option -e
, then enter the sequence \033
:
echo -e "Now this becomes \033[31mRed\033[0m."
Now this becomes RED.
Some important control characters
The following table gives an overview of some useful sequences. Please note that not every terminal emulation can display all attributes correctly. Sometimes, e.g. boldface, is displayed by replacing it with a higher brightness:
\033[0m | Reset all attributes |
\033[1m | Bold |
\033[4m | Underline |
\033[5m | Blink |
\033[7m | Negative |
\033[30m | Text colour Black |
\033[31m | Text colour Red |
\033[32m | Text colour Green |
\033[33m | Text colour Yellow |
\033[34m | Text colour blue |
\033[35m | Text colour Magenta |
\033[36m | Text colour Cyan |
\033[37m | Text colour White |
\033[40m | Background Black |
\033[41m | Background Red |
\033[42m | Background Green |
\033[43m | Background Yellow |
\033[44m | Background Blue |
\033[45m | Background Magenta |
\033[46m | Background Cyan |
\033[47m | Background White |