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
done

This 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 ...

Get Learning the bash Shell, Second Edition 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.