General structure :
trap [[ "command sequence"] n ...]
where "trap" is the command. This is usually coded at the top of the function or shell script but may be coded elsewhere and may be repeated so different control characters are trapped in different parts of the script.
"command sequence" is an optional quoted sequence of semi-colon delimited commands. If command sequence left out or open and closed quotes stated with no commands inside, then trap takes no action for targetted signals. Signals are ignored.
So :
trap 2
in a shell script will prevent a [ctrl]c from interrupting the script.
If you do wish the script or function to terminate after taking special actions for a particular signal, include an exit or return in the command sequence. The command sequence must be quoted.
[[n]..] is a space delimited list of signals to be trapped. See the signal man page, section 7 for a complete list signal definitions and which can be trapped.
If you use 0 or the reserved word EXIT for the signal, the command sequence will run on termination for any reason. Don't use it if you are coding a trap in a function.
For the exercise below, copy the code into a file and make it executable. You may name it what ever you want. For discussion, I will assume it is called "adder". Run it and test it out.
The 1st trap traps [ctrl]c signal and exits with a message and an error status.
The second displays the sum on termination, even if it because of the trapped [ctrl]c.
The third cause the HUP signal to be ignored. Quotes still required.
#!/bin/bash trap 'echo "You should use q"; exit 2' 2 trap 'echo "Your sum is $sum"' EXIT trap '' 1 sum=0 # endless loop, must use break to quit while true do echo -e "Enter a number or q to quit with total :\c" read ans if [ "$ans" = q ] then break fi # Add only if a number, may be negatively signed if test `echo $ans | grep "^-\{0,1\}[0-9][0-9]*$"` then sum=`expr $sum + $ans` fi done The easiest way to test this is to log in to a second terminal. Run "adder" from one terminal. Try entering a few numbers and quit normally. Note the output. Next, restart "adder". From the other terminal run : ps -u $USER and find the process id for adder. Now, issue a kill command with the -HUP option on the process id assigned to "adder". Check back in 1st terminal. "adder" should still be running. Try the same again, except use -INT signal instead. "adder" should now terminate after printing current sum.
|