Bash – Color script output only when invoked from interactive shell

bashcolorsshell-script

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.

Best Answer

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

--color[=WHEN]
              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.