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.
1 Answer 1
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).
exec 2>somefile
at the beginning of the script should suffice.