Question

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?

Était-ce utile?

La solution

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:

rm foo || { echo "File removal failed"; }

Note that most commands will print their own failure notices to standard error.

Autres conseils

I don't think the error trap handler receives any information about the precise error which caused it to run. You can get the exit code from the failed command, but by the time the trap runs, you don't know even which command failed.

You could try to write a simple C program to fetch the latest system error with perror or some such.

... Update: It doesn't work; in retrospect, for obvious reasons. I'll leave this here for coming generations to discover. /-:

vnix$ cat perror.c
#include <stdio.h>
#include <errno.h>

int main (int argc, char **argv)
{
  perror("");
}

vnix$ gcc perror.c

vnix$ touch /fnord
touch: cannot touch `/fnord': Permission denied

vnix$ ./a.out
Success
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top