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

前端 未结 10 1051
独厮守ぢ
独厮守ぢ 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 08:54

    The following will work for KornShell(ksh) where the process substitution is not available,

    # create a combined(stdin and stdout) collector
    exec 3 <> combined.log
    
    # stream stderr instead of stdout to tee, while draining all stdout to the collector
    ./aaa.sh 2>&1 1>&3 | tee -a stderr.log 1>&3
    
    # cleanup collector
    exec 3>&-
    

    The real trick here, is the sequence of the 2>&1 1>&3 which in our case redirects the stderr to stdout and redirects the stdout to descriptor 3. At this point the stderr and stdout are not combined yet.

    In effect, the stderr(as stdin) is passed to tee where it logs to stderr.log and also redirects to descriptor 3.

    And descriptor 3 is logging it to combined.log all the time. So the combined.log contains both stdout and stderr.

提交回复
热议问题