How to Catch Ctrl-C in Shell Script

There are times when you do not want users to stop a running shell script abruptly by sending the Ctrl-C key combination. There is no way to prevent users from doing that, but there is a way to catch or trap Ctrl-C key combinations in a shell script.

UNIX Trap Signal List

UNIX Trap Signal List

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.

#!/bin/sh

# this function is called when Ctrl-C is sent
function trap_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
    exit 2
}

# 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"
sleep 1000
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.

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

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

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }