Shell Terminal – How Programs Decide on Colored Output

colorsprocessshellterminal

When I execute a command from a terminal that prints coloured output (such as ls or gcc), the coloured output is printed. From my understanding, the process is actually outputting ANSI escape codes, and the terminal formats the colour.

However, if I execute the same command by another process (say a custom C application) and redirect the output to the application's own output, these colours do not persist.

How does a program decide whether or not to output text with colour format? Is there some environment variable?

Best Answer

Most such programs only output colour codes to a terminal by default; they check to see if their output is a TTY, using isatty(3). There are usually options to override this behaviour: disable colours in all cases, or enable colours in all cases. For GNU grep for example, --color=never disables colours and --color=always enables them.

In a shell you can perform the same test using the -t test operator: [ -t 1 ] will succeed only if the standard output is a terminal.

Related Question