Bash – Ctrl-C in bash scripts

bashshell-scripting

How do I implement ctrl+c handling in bash scripts so that the script is interrupted, as well as the currently running command launched by the script?

(Imagine there's a script that executes some long-running command. The user hits ctrl+c and interrupts the command, but the script proceeds.) I need it to behave in a way that they are both killed.

Best Answer

You do this by creating a subroutine you want to call when SIGINT is received, and you need to run trap 'subroutinename' INT.

Example:

#!/bin/bash

int_handler()
{
    echo "Interrupted."
    # Kill the parent process of the script.
    kill $PPID
    exit 1
}
trap 'int_handler' INT

while true; do
    sleep 1
    echo "I'm still alive!"
done

# We never reach this part.
exit 0