22

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.

1
  • 1
    If your OS has job-control enabled, another option would be to stop that script (usually with crtl-z). You can continue that job in background with bg, kill it or continue it in foreground with fg. See the bash manpage section JOB CONTROL.
    – ott--
    Nov 5, 2011 at 17:44

1 Answer 1

26

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
3
  • 2
    Note that you can also trap on EXIT in cases where you have something you want to execute anytime the script exits regardless how it stopped. (KILL excepted, of course.)
    – Blrfl
    Nov 5, 2011 at 19:22
  • Great, thanks! However, when 'sleep' is killed — the shell could still be able to manage to execute the next command while the trap routine is running: 'echo' in this case... or I'm wrong?
    – kolypto
    Nov 5, 2011 at 22:54
  • That should not be possible, no. It does not perform tasks in parallel.
    – Kvisle
    Nov 5, 2011 at 23:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .