Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to specify traps other than EXIT?

Tags:

bash

shell

sh

ksh

zsh

I see a lot of shell scripts that do:

 trap cmd 0 1 2 3 13 15 # EXIT HUP INT QUIT PIPE TERM 

In every shell I have access to at the moment, all the traps other than 0 are redundant, and cmd will be executed upon receipt of a signal if the trap is simply specified:

 trap cmd 0 

Is the latter specification sufficient, or do some shells require the other signals to be specified?

like image 594
William Pursell Avatar asked Nov 14 '11 14:11

William Pursell


People also ask

What is trap exit?

For all intents and purposes, if you trap exit, it will be executed when the shell process terminates. Exit the shell, returning a status of n to the shell's parent. If n is omitted, the exit status is that of the last command executed. Any trap on EXIT is executed before the shell terminates.

What is the use of trap command?

The trap command traps a system-generated signal generated by the D3 monitor or by the UNIX kernel and executes a TCL statement. Without any argument, the trap command lists the currently global signals.

Can you trap Sigkill?

You can't catch SIGKILL (and SIGSTOP ), so enabling your custom handler for SIGKILL is moot. You can catch all other signals, so perhaps try to make a design around those. be default pkill will send SIGTERM , not SIGKILL , which obviously can be caught.


2 Answers

I think trap 0 is executed just prior to script termination in all cases, so is useful for cleanup functionality (like removing temporary files, etc). The other signals can have specialized error handling but should terminate the script (that is, call exit).

What you have described, I believe, would actually execute cmd twice. Once for the signal (for example SIGTERM) and once more on exit (trap 0).

I believe the proper way to do this is like the following (see POSIX specification for trap):

trap "rm tmpfile" 0 trap "exit 1" TERM HUP ...  

This ensures a temporary file is removed upon script completion, and lets you set custom exit statuses on signals.

NOTE: trap 0 is called whether a signal is encountered or not.

If you are not concerned with setting an exit status, trap 0 would be sufficient.

like image 162
Brandon Horsley Avatar answered Sep 23 '22 03:09

Brandon Horsley


To make sure the EXIT signal handler will not be executed twice (which is almost always not what you want) it should always set to be ignored or reset within the definition of the EXIT signal handler itself.

The same goes for signals that have more than one signal handler defined for them in a program.

# reset trap 'excode=$?; cmd; trap - EXIT; echo $excode' EXIT HUP INT QUIT PIPE TERM  # ignore trap 'excode=$?; trap "" EXIT; cmd; echo $excode' EXIT HUP INT QUIT PIPE TERM 
like image 35
carlo Avatar answered Sep 22 '22 03:09

carlo