Advanced Bash Redirection + Logging

Just the other day I came across a great post by Travis B. Hartwell regarding how to redirect stdout to stderr to a file while still displaying that output.  Not only does he show how it could be done, he goes through great detail in how his approach works.  Definately a good read for anyone who is trying improve their bashiness.  To read more, especially if you wish to know how it works, go here.

Otherwise here’s the code:

#!/bin/bash
 
OUTPUT_LOG=output.log
OUTPUT_PIPE=output.pipe
 
if [ ! -e $OUTPUT_PIPE ]; then
    mkfifo $OUTPUT_PIPE
fi
 
if [ -e $OUTPUT_LOG ]; then
    rm $OUTPUT_LOG
fi
 
exec 3>&1 4>&2
tee $OUTPUT_LOG < $OUTPUT_PIPE >&3 &
tpid=$!
exec > $OUTPUT_PIPE 2>&1
 
echo "This is on standard out"
echo "This is on standard err" >&2
 
exec 1>&3 3>&- 2>&4 4>&-
wait $tpid
 
rm $OUTPUT_PIPE
This entry was posted in Software Development and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. 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> <pre lang="" line="" escaped="" highlight="">