How to judge whether its STDERR is redirected to a file in a Bash script on Linux?

Within 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).

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *