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.