Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

In bash 4.x If I have:

err_handler() {
    echo You received error $1|mail -s "script error" MAILTO
}

trap err_handler ERR

how do I send the actual stderr output to the function when the trap is called? I want to avoid having to put logic on every line to redirect stderr, thats the point of a trap I think.

share|improve this question
1  
What about redirecting stderr to a file from the beginning (for the complete script), and then just sending the contents of that file on error? As added bonus, if mailing fails for whatever reason, you still have the file locally to look what happened. –  celtschk May 16 at 16:12
    
Uhm, no. The purpose of the trap is to invoke specific behavior when a signal has been received. The signal carries no further data, not from stdout nor stderr of any subprocesses. –  Felix Frank May 16 at 16:13
    
@FelixFrank: From bash's man page: "A SIGNAL_SPEC of ERR means to execute ARG each time a command's failure would cause the shell to exit when the -e option is enabled." So no signal here. And yes, that event itself is also not associated with standard error, but usually failing commands write something to standard error before they exit with non-zero exit status (which is what Gregg Leventhal wants to send). And if you store everything written to standard error by your script into a file, then that file will especially contain the error output of the failing command. –  celtschk May 16 at 16:21
    
I see. My bad. I'm basically with celtschk then. You could just globally redirect all stderr to a file, then include the contents of that in the mail. –  Felix Frank May 16 at 16:30
1  
exec 2>somefile at the beginning of the script should suffice. –  celtschk May 16 at 16:56
show 2 more comments

1 Answer 1

up vote 1 down vote accepted

There is no way to retroactively capture the error output, because at the time the command returns with a non-zero exit status, the output already has been done. However you can redirect all stderr output of your script from the beginning to a file by issuing the command

exec 2>/some/file

at the beginning of your script. This command-less form of exec applies the redirections to the current shell process. You then can send that file in case of an error.

An additional advantage of this method is that if sending the mail fails for any reason, you still have the file around to look at locally (well, unless the reason is a failure of that disk, of course).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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