trap
We’ve been discussing how signals affect the casual user; now let’s talk a bit about how shell programmers can use them. We won’t go into too much depth about this, because it’s really the domain of systems programmers.
We mentioned above that programs in general can be set up to “trap” specific signals and process them in their own way. The trap built-in command lets you do this from within a shell script. trap is most important for “bullet-proofing” large shell programs so that they react appropriately to abnormal events—just as programs in any language should guard against invalid input. It’s also important for certain systems programming tasks, as we’ll see in the next chapter.
The syntax of trap is:
trap cmd sig1 sig2 ...
That is, when any of sig1, sig2, etc., are received, run cmd, then resume execution. After cmd finishes, the script resumes execution just after the command that was interrupted. [113]
Of course, cmd can be a script or function. The sigs can be specified by name or by number. You can also invoke trap without arguments, in which case the shell will print a list of any traps that have been set, using symbolic names for the signals.
Here’s a simple example that shows how trap works. Suppose we have a shell script called loop with this code:
while true; do
sleep 60
doneThis will just pause for 60 seconds (the sleep command) and repeat indefinitely. true is a “do-nothing” command whose exit status is always 0. [114]Try typing in this script. Invoke it, let ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access