The Bourne Again Shell script presented in this article demonstrates techniques related to capturing and logging output (standard output and standard error stream) of a script into a log file while also delivering it to the regular output destinations (for example the terminal or whatever the caller has chosen to redirect to). Some questions are addressed:
- How to „clone“ standard output and standard error stream of a shell script to a single log file?
- Are the messages from both streams interleaved into a single file in the appropriate order?
- Can a script perform output cloning for some portions of its procedure while skipping it for others?
- Are there specific requirements for output that is to be cloned to a file?
- Are there best practices when a script modifies its own output redirections?
The example provided below has been tested on GNU/Linux using GNU „bash“ version 5 and „tee“ version 8.32 from GNU coreutils. It uses the Bash-only feature of process substitution. An implementation in POSIX Shell (possibly using only POSIX tools) would be more difficult.