./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/stderr and testing them with
-f in Bash can judge whether they are redirected to files.
$ 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)"
$ ./check-stdout-stderr.sh >/tmp/a $ cat /tmp/a STDOUT is a file: /proc/25141/fd/pipe:
$ ./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:
The interesting part is that STDOUT redirecting is implemented as a pipe (with caching, I guess).