且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测我的 shell 脚本是否正在通过管道运行?

更新时间:2021-09-07 22:45:46

在纯 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: