docwhat's avatardocwhat's blog

Logging while monitoring a shell script

You may be familiar with redirecting the output of your shell script to a file using exec

However, what do you do if you want monitor the output while logging at the same time? I just figured this out (probably again, since I tend to forget things… which is why I’m blogging this).

WARNING: This is bash-specific. While I prefer ZSH for my personal shell, I generally code in bash because it is everywhere.

# Logs only stdout
exec > >(tee "somefile.log")

# Logs stderr and stdout to separate files.
exec 2> >(tee "somefile.err")
exec > >(tee "somefile.log")

# Logs stderr and stdout to the same file.
exec > >(tee "somefile.log")
exec 2>&1

I got it from Naked Ape’s Shell Hacks.

This is apparently called process substitution.

Ciao!

Edit on GitHub