function loop {
trap 'print "How dare you!"' INT
while true; do
sleep 60
done
}
trap 'print "You hit control-C!"' INT
loop
When you run this script and hit your interrupt key, it
prints "How dare you!" But how about this:
function loop {
while true; do
sleep 60
done
}
trap 'print "You hit control-C!"' INT
loop
print 'exiting ...'
This time the looping code is within a function, and the trap
is set in the surrounding script. If you hit your interrupt key,
it prints the message and then prints "exiting..."
It does not repeat the loop as above.
Why? Remember that when the signal comes in,
the shell aborts the current command, which in this case is a call
to a function. The entire function aborts, and execution
resumes at the next statement after the function call.
The advantage of traps that are local to functions is that they
allow you to control a function's behavior separately from the
surrounding code.
For example, you may want to reset the trap on the signal you just
received, like this: