如何检测我的 shell 脚本是否正在通过管道运行? [英] How can I detect if my shell script is running through a pipe?
问题描述
如何从 shell 脚本中检测其标准输出是发送到终端还是通过管道传输到另一个进程?
How do I detect from within a shell script if its standard output is being sent to a terminal or if it's piped to another process?
恰当的例子:我想添加转义码来为输出着色,但仅在交互式运行时,而不是在管道中运行时,类似于 ls --color
所做的.
The case in point: I'd like to add escape codes to colorize output, but only when run interactively, but not when piped, similar to what ls --color
does.
推荐答案
在纯 POSIX shell 中,
In a pure POSIX shell,
if [ -t 1 ] ; then echo terminal; else echo "not a terminal"; fi
返回终端",因为输出被发送到您的终端,而
returns "terminal", because the output is sent to your terminal, whereas
(if [ -t 1 ] ; then echo terminal; else echo "not a terminal"; fi) | cat
返回非终端",因为括号元素的输出通过管道传送到 cat
.
returns "not a terminal", because the output of the parenthetic element is piped to cat
.
-t
标志在手册页中被描述为
The -t
flag is described in man pages as
-t fd 如果文件描述符 fd 已打开且指向终端,则为真.
-t fd True if file descriptor fd is open and refers to a terminal.
... 其中 fd
可以是通常的文件描述符分配之一:
... where fd
can be one of the usual file descriptor assignments:
这篇关于如何检测我的 shell 脚本是否正在通过管道运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!