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

前端 未结 10 1057
独厮守ぢ
独厮守ぢ 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条回答
  •  Happy的楠姐
    2020-11-22 08:59

    To redirect stderr to a file, display stdout to screen, and also save stdout to a file:

    ./aaa.sh 2>ccc.out | tee ./bbb.out

    EDIT: To display both stderr and stdout to screen and also save both to a file, you can use bash's I/O redirection:

    #!/bin/bash
    
    # Create a new file descriptor 4, pointed at the file
    # which will receive stderr.
    exec 4<>ccc.out
    
    # Also print the contents of this file to screen.
    tail -f ccc.out &
    
    # Run the command; tee stdout as normal, and send stderr
    # to our file descriptor 4.
    ./aaa.sh 2>&4 | tee bbb.out
    
    # Clean up: Close file descriptor 4 and kill tail -f.
    exec 4>&-
    kill %1
    

提交回复
热议问题