Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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
up vote 22 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.



    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!"

# We never reach this part.
exit 0
share|improve this answer
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? – kolypto 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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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