To trap Ctrl-C in a shell script, we will need to use the trap
shell builtin command. When a user sends a Ctrl-C interrupt signal, the signal SIGINT
(Signal number 2) is sent. Let’s see how we can trap this signal in a shell script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/sh # this function is called when Ctrl-C is sent functiontrap_ctrlc () { # perform cleanup here echo"Ctrl-C caught...performing clean up" echo"Doing cleanup" # exit shell script with error code 2 # if omitted, shell script will continue execution exit2 } # initialise trap to call trap_ctrlc function # when signal 2 (SIGINT) is received trap"trap_ctrlc"2 # your script goes here echo"going to sleep" sleep1000 echo"end of sleep" |
First, a function trap_ctrlc ()
is defined in line 4. This function will be called when a Ctrl-C sequence is detected. Any cleanup can be performed in this function. Note the exit
statement within the function. Without this statement, the shell script will continue execution.
Second, the trap
command is initialised with the function name and the signal to catch in line 18.
Below is the output of the script if we send Ctrl-C while the sleep command is being executed.
1 2 3 4 |
[ibrahim@anfield ~] $ ./trapc.sh going to sleep Ctrl-C caught...performing clean up Doing cleanup |
Now, what if we omit the exit
statement in line 13? Below is what we will get.
1 2 3 4 5 |
[ibrahim@anfield ~] $ ./trapc.sh going to sleep Ctrl-C caught...performing clean up Doing cleanup end of sleep |
Note that the echo
command in line 23 is now being executed.