Wednesday 14 October 2009

trap command to catch untimely script exits

trap syntax :
trap [arg] [signal]...

The trap waits for a signal sent to the shell, traps it, and then executes arg. After setting traps, typing trap with no args lists all commands associated with signals.

For example:

$ temp="/tmp/xyz$$"
$ trap "rm -f $temp; exit" 0 2 3 15
$ trap
0:rm -f /tmp/xyz18996; exit
2:rm -f /tmp/xyz18996; exit
3:rm -f /tmp/xyz18996; exit
15:rm -f /tmp/xyz18996; exit


In the first line, a temporary file temp is defined, whose name includes xyz and the process id number. The second line sets a trap to remove the file (without complaining if it doesn't exist yet or if the remove fails). It then exits the shell if the shell exits (0) or receives one of a certain set of signals (2, 3, 15), which could be given by names (INT, QUIT, TERM). After setting the trap, trap with no options, lists all traps. The exit in the trap is necessary because otherwise the trap would be like an interrupt routine, returning to execution of the script on receipt of a signal.

If arg is omitted or is -, all trap signals are reset to their original values. If signal is ERR then arg will be executed whenever a command has a nonzero exit code. The ERR trap is not inherited by functions.

If the signal is 0 or EXIT and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes. If signal is EXIT for a trap set outside any function then the command arg is executed on exit from the shell.

No comments:

Post a Comment

Tweets by @sriramperumalla