Trap: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 15: Line 15:


=Behavior on Being Invoked from Sub-Shells=
=Behavior on Being Invoked from Sub-Shells=
If code is registered with <code>trap</code> in a sub-shell,  or in a function that is invoked in a sub-shell, to react to EXIT, then the registered code will be executed when the sub-shell, and not the top-level invoking shell, exists.
The following code:
<syntaxhighlight lang='bash'>
$(trap 'echo "a" 1>&2' EXIT)
echo "b"
</syntaxhighlight>
will display:
<syntaxhighlight lang='bash'>
a
b
</syntaxhighlight>

Revision as of 19:22, 25 September 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

Also see:

Handling Signals in bash

Behavior on Being Invoked from Sub-Shells

If code is registered with trap in a sub-shell, or in a function that is invoked in a sub-shell, to react to EXIT, 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