3

I can use 2> errorLogFile to log error of running script to a file right? my question is how to log the date and time of error along with error?

for example:

$ cat myScript
2> errorLogFile
..... # rest of the script

this is how the error file should look like:

$ cat errorLogFile
21 Nov 2015 2:00 PM some error happened

1 Answer 1

0

You could redirect stderr to a process substitution which processes stderr and outputs the processed lines to the log.

For example, this script will print 5 lines to stdout and 5 lines to stderr, redirecting stderr to a process susbstitution which processes stderr and outputs the processed lines to a file named "log" in the current working directory (mind that the syntax to redirect stderr is exec 2> [...], not 2> [...]):

#!/bin/bash
exec 2> >(perl -pe '$x=`date "+%d %b %Y %H:%M %p"`;chomp($x);$_=$x." ".$_' >log)
for i in {1..5}; do
    sleep 1
    echo "STDOUT message #$i"
    echo "STDERR message #$i" >&2
done
exit 0

The process substitution invokes Perl, which appends the current date and time in that format to each line and outputs them to a file named "log" in the current working directory.

% bash script.sh
STDOUT message #1
STDOUT message #2
STDOUT message #3
STDOUT message #4
STDOUT message #5
% cat log
02 Nov 2015 20:15 PM STDERR message #1
02 Nov 2015 20:15 PM STDERR message #2
02 Nov 2015 20:15 PM STDERR message #3
02 Nov 2015 20:15 PM STDERR message #4
02 Nov 2015 20:15 PM STDERR message #5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.