Up until recently I was under the impression that Unix-y programs were unaware of where their output went, be it to standard out, redirected to a file, or into a pipe. However, an unrelated U&L question on this site brought to my attention the following example:% echo hello world > file% grep --color=auto lo filehello world% grep --color=auto lo file | cathello worldObviously you can't see it here, but the first command shows 'lo' highlighted, as expected. However, the second call, which goes through a pipe, shows no colour. This suggests that grep was aware of its output being directed to a pipe and avoided outputting colour. How is this done?
Are unix[-like] programs capable of determing where their output is going?
terminal;io redirection;colors;stdout;stdin
It is possible to determine whether a file descriptor refers to a tty.Check out the isatty function.Alternatively, you can use the fstat function which gives you a chunk of information on the file.