简体   繁体   中英

Redirect copy of stdout and stderr to one file, copy of just stderr to another file from within bash script

Note that I have reviewed both stackoverflow questions below, but my question is different:

In attempting to do this, I have the following test.sh script:

#!/bin/bash

rm stdout_and_stderr.log
rm stderr.log

exec 2> >(tee -ia stderr.log >> stdout_and_stderr.log) 1> >(tee -ia stdout_and_stderr.log)

echo "stdout"
echo "stderr" >&2

The only problem is that stderr is not displayed to terminal:

$ ./test.sh > /dev/null
$ ./test.sh 2> /dev/null
$ stdout

My version of bash:

GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)

Here is a solution that works:

#!/bin/bash

rm stdout_and_stderr.log
rm stderr.log

exec 2> >(tee -ia stdout_and_stderr.log >&2)
exec 2> >(tee -ia stderr.log >&2)
exec 1> >(tee -ia stdout_and_stderr.log)

echo "stdout"
echo "stderr" >&2

It can also be done in one line:

exec 1> >(tee -ia stdout_and_stderr.log) 2> >(tee -ia stdout_and_stderr.log >&2) 2> >(tee -ia stderr.log >&2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM