Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

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 file
hello world

% grep --color=auto lo file | cat
hello world

Obviously 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?

share|improve this question

marked as duplicate by Gilles linux Sep 2 '15 at 22:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

See ls command operating differently depending on recipient for a similar discussion. – manatwork Mar 23 '12 at 14:51
The key is that classic command-line oriented unix programs can operate without knowing or caring what their stdin and stdout filehandles refer to, not that they must remain unaware. Besides color, tools like ls and grep will also treat whitespace differently if they think they're talking to a 2-dimensional console rather than a 1-dimensional file stream. – Russell Borogove Mar 23 '12 at 17:42
up vote 11 down vote accepted

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.

share|improve this answer
Awesome -- thanks! – noffle Mar 23 '12 at 15:43

Yes, they are. There are several methods to determine where the output is going. For a comparison see my answer to a related question on stackoverflow.

share|improve this answer
Great, in-depth answer. – noffle Mar 23 '12 at 19:26

Easily. Different ways can be used to determine where the output is going. So in python you could do something like

    /* CODE. Input will be parsed and executed */
PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
                     PyCompilerFlags *flags)
    if (filename == NULL)
        filename = "???";
    if (Py_FdIsInteractive(fp, filename)) {
        int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.