Output Color on Bash Scripts – Advanced
I talked in a previous post about basic bash script colored output using the tput command. The tput command works for basic coloring (providing seven colors to choose from) but ANSI also provides a 256 color palette.
ANSI color coding is in this form:
The ANSI sequence: {ESC}[{attr};{bg};{256colors};{fg}m
{ESC} or \033 represents the ANSI escape-sequence. {attr} represents the outputs attributes (properties such as blinking and bold text), {fg} is the foreground color, {bg} is the background color, m means the sequence ends.
An example:
echo -e "My favorite color is \033[38;5;148mYellow-Green\033[39m"
The variable -e is required because echo doesn’t normally interpret backslashes and 033[39m tells bash to end the seqeunce. The 38 Value will use no background color. Notice too that I omitted the attribution value which if isn’t used will use the default (regular text) value.
To get color values a good program is colortest.
Colortest will show the ANSI color value to the corresponding hex value. Then just insert the ANSI value into the either the foreground or background value.
There’s also a program called conv-rgb2xterm that a hex value can be put in and it will give and ANSI sequence for the foreground color.
References:
- ANSI Attributes (look at graphic parameters)
- So You Like Color–The Mysterious ^[[ Characters
- Colorizing Scripts
- Tput Usage(Thanks to arcanex for pointing me on how to use the tput command!)


grim said,
August 14, 2008 at 2:54 pm
hi! Pretty much thanks for the scripts!
I’ve found urxvt to not support all 256 colors, only 88 :(
Time to change software it seems…
Anyway, about the colors I found quite recently that ANSI sequences can be used almost anywhere.
One important for me is /etc/motd and my.cnf.
You just compose the bare text and then add colors with ANSI-sequences.