Are unix[-like] programs capable of determing where their output is going?

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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.

Solution 3

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);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply