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
this is equal to
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 aftercommand 2
finished even ifcommand 1
is still running.You probably want
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 orwait
in my version.I would suggest setting a trap like this:
With the trap the SIGINT signal produced by CTRL-C is trapped and replaced by the
killgroup
function, which kills all those processes.