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

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
| 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? – 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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