Link Search Menu Expand Document

How to test for colors in shell scripts

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. Using colors in a script with tput or escape sequences is quite easy, but you also want to check when not to use colors to avoid messing up terminals not supporting them or when logging to a file.

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
or using tput
$ TERM=vt100 tput colors

$ TERM=linux tput colors
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


# Check wether stdout is redirected
if [ ! -t 1 ]; then

max_colors=$(tput colors)
if [ $max_colors -lt 8 ]; then 

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.