在Linux中,如何测试程序的输出是进入实时终端还是文件? [英] In linux, how can I test whether the output of a program is going to a live terminal or to a file?

查看:123
本文介绍了在Linux中,如何测试程序的输出是进入实时终端还是文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用 git 时,它似乎神奇地知道标准输出是否正在通过管道或文件,以及将其显示在控制台上的时间.例如,如果您启用了颜色并且执行了

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

git status > status.txt

它删除了 Linux颜色格式,而您只看到纯色的文本.

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

git如何检测其命令输出是否要归档到终端?

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

推荐答案

isatty(int fd)将检查fd是否引用终端或其他内容.它是GNU C库中unistd.h的一部分.

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.

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

顺便说一句:如果您想使用另一个程序来阅读一个程序,但又想愚弄isatty认为您的程序是人类,那么有一种方法可以做到这一点.您可以使用伪终端(pty).例如,期望使用此技术.

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.

这篇关于在Linux中,如何测试程序的输出是进入实时终端还是文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆