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 SupportThere 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 8tput is propably the best choice.
Checking the TerminalSo 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.