If you use bash colors, check for a tty first!

Most of the command line programs I write use ANSI escape codes to output colored text (along with bold/underlined text). I find this makes the programs a lot easier to understand at a glance. For example, my test runners will output success in green, skipped in yellow, and failure in red. I can very quickly scroll through the output and spot failures.

However, if you’re going to do this, or if you already do this, you may run into problems with redirecting your program to a log file or piping it to another program. Your colors show up as ugly escape codes and make it harder to parse the log files. Pretty frequently, you only want colors if you’re outputting to an interactive terminal.

When you use colors in your command line program, you should support two features. Your program should have an option to disable colors, such as –no-color, and you should automatically detect if STDOUT is a TTY, and if not, disable colors.

Here’s a PHP example:

// Disable colors
if (in_array('--no-color', $argv) || !posix_isatty(STDOUT)) {
  $runner->color = false;

And here’s a Python example:

if not sys.stdout.isatty():
  color_mode = False

Since stdout won’t be a TTY if you are using redirection or piping, it’s a good thing to check before using color codes.

Leave a Reply