I want to trap the error inside the shell script, and then generate some report for the reason for the error:
trap 'error_handler' ERR
In my error_handler function, I want to give the reason for why the ERR signal was caught (e.g. “permission denied”, “cannot find remote host”, etc.).
Is this possible?
Not really. The only piece of information you are guaranteed to have available in your error handler is the exit status of the process that triggered the
ERR, in$?. You don’t even know the name of the process or its process ID. I think the error handler is meant for general purpose clean-up before exiting a script, so it doesn’t matter which process had the non-zero exit status or why.You are better off reporting on or dealing with errors immediately when they happen, like so:
Note that most commands will print their own failure notices to standard error.