Shell Script IO Redirection – Redirect Script Stderr & Stdout to File but Keep Stdout to TTY

io-redirectionshell-script

In my script, I currently have:

exec > >(tee -a /tmp/history.log) 2>&1

This writes both the stderr and stdout of all commands to both the log file and the tty. Unfortunately, this makes the tty very noisy, so I'd rather have only stdout on the terminal and both stdout and stderr in the file (in correct order, so opening the file twice for append won't work). For the life of me, I can't figure out the magic exec invocation (even using tee /dev/tty) necessary to get this to work.

Best Answer

tee can't directly output to a file descriptor, but you can use process substitution with cat to solve it:

exec 3>&1 &>log 1> >(tee >(cat >&3))

So, stdout goes to the output through fd3, and both stdout and stderr go the log.

Related Question