stderr 重定向
Within a Bash script, how to judge whether its STDERR is redirected to a file in Bash on Linux?
在Bash脚本中,如何判断其STDERR是否已重定向到Linux上Bash中的文件?
For example,
例如,
./script.sh /tmp/log 2>&1
Can script.sh detect that its STDERR is redirected? Knowing the destination file is better.
script.sh是否可以检测到其STDERR被重定向? 了解目标文件会更好。
To test whether a script’s STDERR (or STDOUT) is redirected to a file, check by
要测试脚本的STDERR(或STDOUT )是否重定向到文件,请通过
[[ -f /dev/stderr ]]
A process’ STDOUT and STDERR are /dev/stdout
and /dev/stderr
and testing them with -f
in Bash can judge whether they are redirected to files.
进程的STDOUT和STDERR是/dev/stdout
和/dev/stderr
,在Bash中用-f
测试它们可以判断它们是否重定向到文件 。
An example:
一个例子:
$ cat check-stdout-stderr.sh
#!/bin/bash
# Author: Eric Zhiqiang Ma
[[ -f /dev/stderr ]] && echo "STDERR is a file: $(readlink -f /dev/stderr)"
[[ -f /dev/stdout ]] && echo "STDOUT is a file: $(readlink -f /dev/stdout)"
Tries:
尝试:
$ ./check-stdout-stderr.sh
outputs nothing.
什么都不输出。
$ ./check-stdout-stderr.sh >/tmp/a
$ cat /tmp/a
STDOUT is a file: /proc/25141/fd/pipe:[2397415]
and
和
$ ./check-stdout-stderr.sh >/tmp/a 2>/tmp/b
$ cat /tmp/a
STDERR is a file: /tmp/b
STDOUT is a file: /proc/25159/fd/pipe:[2393867]
The interesting part is that STDOUT redirecting is implemented as a pipe (with caching, I guess).
有趣的是STDOUT重定向是通过管道实现的(我想是带有缓存的)。
stderr 重定向