Bash: How to catch the cause of the error?

I want to catch an error inside a shell script, and then generate some report due to an error:

trap 'error_handler' ERR 

In my error_handler function error_handler I want to indicate the reason why the ERR signal was found (for example, "permission is allowed", "cannot find the remote host", etc.).

Is it possible?

+4
source share
2 answers

Not really. The only piece of information that you are guaranteed to be available in your error handler is the exit status of the process that caused ERR , in $? . You do not even know the name of the process or its process identifier. I think the error handler is intended for general purpose cleaning before exiting the script, so it doesn't matter which process had a non-zero exit status or why.

You are better off reporting errors immediately when they occur, for example:

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

Note that most teams will display their own standard error notifications.

+3
source

I do not think that the error error handler receives any information about the exact error that made it work. You can get the exit code from the failed command, but by the time the trap starts, you do not know which command was not executed.

You can try writing a simple C program to get the latest system error using perror or some of these.

... Update: it does not work; in retrospect, for obvious reasons. I will leave it here for future generations. / -:

 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 
+1
source

All Articles