27 Jul 2007 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:



if [ ! -e $OUTPUT_PIPE ]; then
    mkfifo $OUTPUT_PIPE

if [ -e $OUTPUT_LOG ]; then
    rm $OUTPUT_LOG

exec 3>&1 4>&2
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


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 2007-07-27 00:46: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!