I made a bash script producing colored output. The colors are fine when the script is called from an interactive shell. However, if the output is processed in another script, or passed through a pipe, it should not be colored (I think).

How is this handled usually? Should I provide an option to turn on/off the colored output, or is there a way to detect this automatically in the script? Preferably it works automatically and I only need a minimum of code to output colored / non-colored, depending on the script invocation...

One problem with automatic detection seems to be that a script always runs non-interactive, so I would have to know the interactive status of the parent shell instead.


1 Answer 1


It is common for unix application that do support colour output (such as grep and ls) to have a command line option as well as possibly automatic detection.

looking at man ls we see

              colorize the output.  WHEN defaults to `always' or can be `never' or `auto'.  More info below

So by default ls will always use colour, notice the auto option.

man grep shows similar

 --color[=WHEN], --colour[=WHEN]
              <snipped> WHEN is never, always, or auto.

If the auto option is enabled (which for your application could be the default) then something like the following answer (suggested by Gilles) may be what you are looking for https://unix.stackexchange.com/a/10065/4635

That is if your output is a terminal and supports colour, and the user hasn't disabled it you should use color. Of course the user using always or never skips this check.

I find it useful if programs have a --color=always even if they support automatic detection, as this means that I can force colour usage 'when I know better' (say my destination isn't a terminal but I know it supports colour'). On some systems I have an alias for ls to ls --color=always.

  • Sounds good. Also, the question suggested by Gilles does not really apply, but Mikel's answer to the question does. So all I needed is if [ -t 1 ] to check whether the output is printed directly, or being post-processed. I'll add that --color option as you suggested. Dec 30, 2012 at 0:15
  • @deepc I was actually referring to Mikel's answer, sorry for not specifying. I have corrected my answer to make it explicit. Cheers.
    – cjh
    Dec 30, 2012 at 0:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .