26.3. trap

The trap command allows you to trap incoming signals to your scripts. The format of the trap command is:

trap name signal(s) 

The name is a list of instructions to be performed when the signal is caught. In reality a function should be called that deals specifically with trapped signals. The name should be surrounded by double quotes (" "). The signal(s) are the incoming signals.

When a signal is trapped a script will generally be in the middle of some processing. The most common form of action to take is:

1.
Clean up temporary files.
2.
Ignore the signals.
3.
Ask the user if the script is really to be terminated.

Here’s a table of the most common trap usages:

trap " " 2 3 Ignore the signals 2 and 3; user cannot terminate
trap ...

Get Linux and Unix Shell Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.