在linux中,如何测试程序的输出是转到实时终端还是文件?

Ros*_*ers 8 linux terminal xterm gnome-terminal konsole

当你使用git时,它似乎神奇地知道标准输出是通过管道还是文件与显示到控制台时.例如,如果您启用了颜色,那么就可以

git status
Run Code Online (Sandbox Code Playgroud)

它将为列出的不同类别的文件着色输出.但是,如果你这样做

git status | less
Run Code Online (Sandbox Code Playgroud)

要么

git status > status.txt
Run Code Online (Sandbox Code Playgroud)

它删除了linux颜色格式,你只能看到简单,无色的文本.

如何git检测其命令的输出是否要转发到终端?

res*_*dsk 14

isatty(int fd)将检查fd是指终端还是其他东西.它是unistd.hGNU C库中的一部分.

手册页:http://linux.die.net/man/3/isatty

isatty顺便说一句:如果您想使用其他程序从程序中读取,但是您想要愚弄您认为您的程序是人类,那么有一种方法可以做到这一点.您可以使用伪终端(pty).例如,期望使用该技术.


t0m*_*13b 8

这是一个C代码,用于演示如何检测标准输出是否被重定向:

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... */
}

这就是git知道输出是转到终端还是文件的方式.