是否检测stdout是否重定向到管道(而不是文件,字符设备,终端或套接字)? [英] Detect if stdout is redirected to a pipe (not to a file, character device, terminal, or socket)?
问题描述
理想情况下,这可以在shell中编写脚本,但是Perl或Python可以. C代码可能会有所帮助,但可能会降低成本/收益.
Ideally, this would be scriptable in shell, but Perl or Python would be fine. C code could be helpful, but probably fails cost/benefit.
我认识到重定向到FIFO(命名管道)可能与真实管道没有区别, 这足以说明我根本不在乎的情况.
I recognize that redirection to a FIFO (named pipe) may be indistinguishable from a real pipe, and that is enough of an edge case that I don't really care.
严格的POSIX解决方案是最好的,而与UNIX/Linux无关的方案是最好的,但是我现在至少需要在Darwin(MacOS X)上可以使用的解决方案.
Strict POSIX solutions are best, UNIX/Linux variant-independent are next best, but at least something that works on Darwin (MacOS X) is what I need right now.
Before you write your answer - I already know about test -t
- that will tell me whether stdout is a terminal (in which case it is definitely not a pipe - but it will not tell me whether stdout has been redirected to a file, non-terminal character device, or UNIX-domain socket rather than a pipe.
预期的用例:我有一个命令应在外壳的反引号内运行,
这样它就可以输出设置环境变量的命令.
如果标准输出未重定向到管道,我希望该命令以错误中止,
那样的话,它肯定不会被eval `mycommand`;
调用.
Intended use case: I have a command that should be run within backquotes in the shell,
so that it can output commands that set environment variables.
I would like the command to abort with an error if stdout is not redirected to a pipe,
as in that case it definitely wasn't invoked by eval `mycommand`;
.
如果在反引号内运行命令时,shell会设置一些特殊的环境变量会有所帮助,但是由于它可能特定于bash或zsh或某些东西,因此管道检测更为重要.
If there's some special environment variable that a shell will set when running a command within backquotes that would be helpful, but as it is likely to be specific to bash or zsh or something, pipe-detection is more important.
推荐答案
(我的评论根据Alex Dupuy的建议进行了回答)
既然您说过可以使用perl,我想您可以使用它的-p文件测试运算符( perldoc. perl.org/functions/-X.html );像perl -e 'exit(-p STDOUT ? 0 : 1);'
这样的东西会告诉您stdout是管道还是fifo(没有区分它们).
(my comment turned to answer per Alex Dupuy's suggestion)
Since you said you can use perl, I guess you can use its -p file test operator (perldoc.perl.org/functions/-X.html); something like perl -e 'exit(-p STDOUT ? 0 : 1);'
will tell you if stdout if a pipe or a fifo (without distinguishing between them).
首先,从shell调用它正是我使用perl -e
的原因:)
Fwiw, calling that from the shell is exactly the reason why I used perl -e
:)
这篇关于是否检测stdout是否重定向到管道(而不是文件,字符设备,终端或套接字)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!