How do I implement Ctrl-C handling in bash scripts so that the script interrupts as well as the currently running command, launched by it?

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

link|improve this question

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 '11 at 17:44
feedback

1 Answer

up vote 19 down vote accepted

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
link|improve this answer
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 '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? – o_O Tync Nov 5 '11 at 22:54
That should not be possible, no. It does not perform tasks in parallel. – Kvisle Nov 5 '11 at 23:02
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.