Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In linux, how can I test whether the output of a program is going to a live terminal or to a file?

When you use git it seems to magically know whether standard out is going through a pipe or into a file vs when it is being displayed to the console. For example, if you have colors enabled and you do

git status

it will colorize the output for different categories of files being listed. However, if you do

git status | less

or

git status > status.txt

it removes the linux color formatting and you only see plain, uncolored text.

How does git detect whether the output of its commands are going to file vs going to the terminal?

like image 249
Ross Rogers Avatar asked Jan 26 '10 21:01

Ross Rogers


2 Answers

isatty(int fd) will check whether the fd refers to a terminal or something else. It's part of unistd.h in the GNU C library.

Man page: http://linux.die.net/man/3/isatty

As an aside: if you want to read from a program using another program, but you want to fool isatty into thinking that your program is a human, there is a way to do that. You can use a pseudo-terminal (pty). This technique is used by expect, for example.

like image 191
rescdsk Avatar answered Oct 25 '22 04:10

rescdsk


This is a C Code to demonstrate how to detect if standard output is redirected:

int main(int argc, char **argv){
    if (!isatty(fileno(stdout))){
      fprintf(stdout, "argv, argc, someone is redirecting me elsewhere...\n");
      return 1;
    }
    /* rest of C code here... */
}

That is how git knows whether the output is going to the terminal or to a file.

like image 29
t0mm13b Avatar answered Oct 25 '22 04:10

t0mm13b