tags:

views:

1179

answers:

2

Right now I'm using exec to redirect stderr to an error log with

exec 2>> ${errorLog}

The only downside is that I have to start each run with a timestamp since exec just pushes the text straight into the log file. Is there a way to redirect stderr but allow me to append text to it, such as a time stamp?

+3  A: 

This is very interesting. I've asked a guy who knows bash quite well, and he told me this way:

 foo() { while IFS='' read -r line; do echo "$(date) $line" >> file.txt; done; };

First, that creates a function reading one line of raw input from stdin, while the assignment to IFS makes it doesn't ignore blanks. Having read one line, it outputs it with the appropriate data prepended. Then you have to tell bash to redirect stderr into that function:

exec 2> >(foo)

Everything you write into stderr will now go through the foo function. Note when you do it in an interactive shell, you won't see the prompt anymore, because it's printed to stderr, and the read in foo is line buffered :)

Johannes Schaub - litb
A: 

I was just looking for the same little neat thing. After seeing this post, I saw another approach that looks promising, too: http://utcc.utoronto.ca/~cks/space/blog/unix/PipingJustStderr