Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append text to stderr redirects in bash

Tags:

bash

stderr

exec

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?

like image 878
dragonmantank Avatar asked Jan 07 '09 13:01

dragonmantank


People also ask

How do I redirect stderr and stdout to a file in bash?

Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.

How do I redirect to stderr?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


1 Answers

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 :)

like image 168
Johannes Schaub - litb Avatar answered Oct 08 '22 01:10

Johannes Schaub - litb