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!

This entry was posted in My Projects and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting