Site icon Database Tutorials

How to Catch Ctrl-C in Shell Script

 

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

 

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.

 

Now, what if we omit the exit statement in line 13? Below is what we will get.

 

Note that the echo command in line 23 is now being executed.

Exit mobile version