Disclaimer : All the postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions.
 

There exists a very handy shell command trap … which could be used to ease “error handling” in shell scripts.
This command can do all of this as defined in the help page of the command ( http://www.computerhope.com/unix/utrap.htm ) :


Defines and activates handlers to be run when the shell receives signals or other conditions.

It is used to register a function that would be invoked on receiving a certain signal or condition within the shell script.
There are some very good articles on the web about certain use-cases of trap. Noticeable ones being :
From linuxcommand.org : http://linuxcommand.org/wss0160.php
IBM DW Article : http://www.ibm.com/developerworks/aix/library/au-usingtraps/

The purpose of this article is to highlight the usefulness of this command for “error handling” in shell scripts.

Using a very trivial example I’ll show a sample use case of “shell script using trap” :

In the above example script, I have defined a function named sh_error() which gets called if any of the functions in this script fails with a non-zero return code.

How does it happen ?
It happens because of this command in the script : trap sh_error ERR

How does it help ?
This facility could be used to take certain action on the event of any function failing i.e. returning non-zero value.
In this example script, the code does not handle the case if the path referred for GLOBAL_LOG_FILE does not exist. So, instead of continuing to the next function this script would fail.

Show me the result ?
Below is the snippet of execution on how the script would behave(with debugging enabled, for easier understanding) if the path to GLOBAL_LOG_FILE didn’t exist. Since the function append_contents_to_master_copy() failed with a non-zero error, the script was TRAPPED by trap routine for ERR case; and the script did not run to completion.

How does this script behave if the path to GLOBAL_LOG_FILE actually exists ?
It would complete normally; and here is the result of that case :

Of course, it is not a very good script; but sufficient enough to demonstrate the use-case, I suppose !


trap command is also very useful for handling signals in scripts e.g. what to do if a script was interrupted by the user i.e. “ctrl+c”.
For that case, the code could need to have a handler function for SIGINT signal and register it using the trap command in the very beginning of the script.
And the registered handler function could probably log the action somewhere and/or do some cleanup.

 

 

What do you think ?

Set your Twitter account name in your settings to use the TwitterBar Section.
%d bloggers like this: