Shell – Ctrl-C with two simultaneous commands in bash

background-processprocess-managementshellsignals

I want to run two commands simultaneously in bash on a Linux machine. Therefore in my ./execute.sh bash script I put:

command 1 & command 2
echo "done"

However when I want to stop the bash script and hit Ctrl+C, only the second command is stopped. The first command keeps running.
How do I make sure that the complete bash script is stopped? Or in any case, how do I stop both commands? Because in this case no matter how often I press Ctrl+C the command keeps running and I am forced to close the terminal.

Best Answer

If you type

command 1 & command 2

this is equal to

command 1 &
command 2

i.e. this will run the first command in background and then runs the second command in foreground. Especially this means, that your echo "done" is printed after command 2 finished even if command 1 is still running.

You probably want

command 1 &
command 2 &
wait
echo "done"

This will run both commands in background and wait for both to complete.


If you press CTRL-C this will only send the SIGINT signal to the foreground process, i.e. command 2 in your version or wait in my version.

I would suggest setting a trap like this:

#!/bin/bash

trap killgroup SIGINT

killgroup(){
  echo killing...
  kill 0
}

loop(){
  echo $1
  sleep $1
  loop $1
}

loop 1 &
loop 2 &
wait

With the trap the SIGINT signal produced by CTRL-C is trapped and replaced by the killgroup function, which kills all those processes.