8

I am having an issue with terminating the execution of a process inside a bash script.

Basically my script does the following actions:

  1. Issue some starting commands
  2. Start a program who waits for CTRL+C to stop
  3. Do some post-processing on data retreived by the program

My problem is that when I hit CTRL+C the whole script terminates, not just the "inner" program.

I have seen around some scripts that do this, this is why I think it's possible.

1
  • 1
    Hint: trap your-ctrlc-handler-function SIGINT Commented May 10, 2016 at 16:22

1 Answer 1

6

You can set up a signal handler using trap:

trap 'myFunction arg1 arg2 ...' SIGINT; 

I suggest keeping your script abortable overall, which you can do by using a simple boolean:

#!/bin/bash # define signal handler and its variable allowAbort=true; myInterruptHandler() { if $allowAbort; then exit 1; fi; } # register signal handler trap myInterruptHandler SIGINT; # some commands... # before calling the inner program, # disable the abortability of the script allowAbort=false; # now call your program ./my-inner-program # and now make the script abortable again allowAbort=true; # some more commands... 

In order to reduce the likelihood of messing up with allowAbort, or just to keep it a bit cleaner, you can define a wrapper function to do the job for you:

#!/bin/bash # define signal handler and its variable allowAbort=true; myInterruptHandler() { if $allowAbort; then exit 1; fi; } # register signal handler trap myInterruptHandler SIGINT; # wrapper wrapInterruptable() { # disable the abortability of the script allowAbort=false; # run the passed arguments 1:1 "$@"; # save the returned value local ret=$?; # make the script abortable again allowAbort=true; # and return return "$ret"; } # call your program wrapInterruptable ./my-inner-program 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.