3 Dec 2006 Nafai77   » (Journeyer)

Redirecting stderr and stdout to a file plus displaying them

It has taken me ages to figure this out. Googling has been fruitless. Finally, after some tinkering, I was able to figure out how to properly redirect stdout and stderr to a file plus display them from within a script. Here's the idiom:

  #!/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

It works but it might not be entirely correct, particularly the exec &> /dev/null. Improvements or suggestions are welcome.

Update: Figured it out. I had to store stderr and then restore stdout and stderr and close the fd that I stored them in.

Update update: Looked back and realized I had a typo on my first exec line.

Syndicated 2006-07-14 08:23:00 from Travis B. Hartwell / Software Craftsman

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!