Trap: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 14: Line 14:
For a list of signals that can be handled, see: {{Internal|Linux_Signals|Linux Signals}}
For a list of signals that can be handled, see: {{Internal|Linux_Signals|Linux Signals}}


<font color=darkgray>EXIT is not a signal, interpret that.</font>
<font color=darkgray>EXIT is not a signal, further investigate that.</font>


Also see: {{Internal|Handling Signals in bash|Handling Signals in bash}}
Also see: {{Internal|Handling Signals in bash|Handling Signals in bash}}

Revision as of 18:11, 5 December 2019

Internal

Overview

Trap is a facility to instruct bash to catch signals and execute code depending on the signal. A common usage in shell scripts is to prevent those scripts to exit untimely when users type keyboard abort sequences, but run cleanup code instead.

Example:

trap 'rm -f ./lock' EXIT

For a list of signals that can be handled, see:

Linux Signals

EXIT is not a signal, further investigate that.

Also see:

Handling Signals in bash

Behavior on Being Invoked from Sub-Shells

If code is registered with trap to react to EXIT in a sub-shell, or in a function that is invoked in a sub-shell, then the registered code will be executed when the sub-shell, and not the top-level invoking shell, exists.

The following code:

$(trap 'echo "a" 1>&2' EXIT)
echo "b"

will display:

a
b

Note that the output should be sent to stderr in the trap code - if the output is sent to stdout, the output is lost, even if the code executes.

TODO

Reactive Wait Container

Investigate usefulness in case of a reactive wait container. Also see Docker Concepts - Container Exit.

CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"