Unix administration stuff that was hard to find out using Google and caused a lot of try and error. Hereby given back to the net...
How to Test for Colors in Shell Scripts
Submitted by Lars Windolf on 9. October 2012 - 22:13.
When watching thousands of log lines from some long running script you might want to have color coding to highlight new sections of the process or to have errors standing out when scrolling through the terminal buffer.
How to Check for Terminal Support
There are at least the following two ways to check for color support. The first variant is using infocmp
$ TERM=linux infocmp -L1 | grep color [...] max_colors#8, [...]
or using tput
$ TERM=vt100 tput colors -1 $ TERM=linux tput colors 8
tput is propably the best choice.
Checking the Terminal
So a sane check for color support along with a check for output redirection could look like this
#!/bin/bash use_colors=1 # Check wether stdout is redirected if [ ! -t 1 ]; then use_colors=0 fi max_colors=$(tput colors) if [ $max_colors -lt 8 ]; then use_colors=0 fi [...]
This should ensure no ANSI sequences ending up in your logs while still printing colors on every capable terminal.
Use More Colors!
And finally if normal colors are not enough for you: use the secret 256 color mode of your terminal! I'm not sure how to test for this but it seems to be related to the "max_pairs" terminal capability listed by infocmp.