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.

HopelessN00b
  • 53,385
  • 32
  • 133
  • 208
kolypto
  • 10,738
  • 12
  • 51
  • 66
  • 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 05 '11 at 17:44

1 Answers1

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
Kvisle
  • 4,113
  • 23
  • 25
  • 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 05 '11 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 05 '11 at 22:54
  • That should not be possible, no. It does not perform tasks in parallel. – Kvisle Nov 05 '11 at 23:02