如何如果我的shell脚本通过管道运行检测? [英] How to detect if my shell script is running through a pipe?
问题描述
我如何从一个shell脚本中检测是否它的标准输出目标定位终端或如果它输送到另一个进程? (举个例子:我想补充逃生codeS上色输出,但只有当交互运行,而不是在管道,类似于什么 LS --color
一样。)
How do I detect from within a shell script if its standard output is targetting a terminal or if it's piped to another process? (Case in point: I'd like to add escape codes to colorize output, but only when run interactively, but not when piped, similarly to what ls --color
does.)
推荐答案
纯POSIX外壳:
if [ -t 1 ] ; then echo terminal; fi
返回终端,因为输出直接去你的,而
returns "terminal", because the output is going straight to you, while
(if [ -t 1 ] ; then echo terminal; fi) | cat
返回任何内容,因为输出将会猫
。
-t标志在手册页描述为
The -t flag is described in the man pages as
-t FD真,如果文件描述符fd是打开的,指的是一个终端。
-t fd True if file descriptor fd is open and refers to a terminal.
和我利用平时的文件描述符分配
and I take advantage of the usual file descriptor assignments
0: stdin
1: stdout
2: stderr
这篇关于如何如果我的shell脚本通过管道运行检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!