How do I write stderr to a file while using “tee” with a pipe?

前端 未结 10 1052
独厮守ぢ
独厮守ぢ 2020-11-22 08:01

I know how to use tee to write the output (STDOUT) of aaa.sh to bbb.out, while still displaying it in the terminal:

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 09:00

    In my case, a script was running command while redirecting both stdout and stderr to a file, something like:

    cmd > log 2>&1
    

    I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1 and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout and stderr to different files, which is not what I want, but it helped me to come up with the exact solution that I need:

    (cmd 2> >(tee /dev/stderr)) > log
    

    With the above, log will have a copy of both stdout and stderr and I can capture stderr from my script without having to worry about stdout.

提交回复
热议问题