How to judge whether its STDERR is redirected to a file in a Bash script on Linux?
Posted on In QAWithin a Bash script, how to judge whether its STDERR is redirected to a file in Bash on Linux?
For example,
./script.sh /tmp/log 2>&1
Can script.sh detect that its STDERR is redirected? Knowing the destination file is better.
To test whether a script’s STDERR (or STDOUT) is redirected to a file, check by
[[ -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.
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).