I have a simple bash script that starts two servers:
#!/bin/bash
(cd ./frontend && gulp serve) & (cd ./backend && gulp serve --verbose)
If the second command exits, it seems that the first command continues running.
How can I change this so that if either command exits, the other is terminated?
Note that we don't need to check the error levels of the background processes, just whether they have exited.
Best Answer
This starts both processes, waits for the first one that finishes and then kills the other:
How it works
Start:
The above two commands start both processes in background.
Wait
This waits for either background job to terminate.
Because of the
-n
option, this requires bash 4.3 or better.Kill
This kills any job for which the current process is the parent. In other words, this kills any background process that is still running.
If your system does not have
pkill
, try replacing this line with:which also kills the current process group.
Easily testable example
By changing the script, we can test it even without
gulp
installed:The above script can be run as
bash script.sh 1 3
and the first process terminates first. Alternatively, one can run it asbash script.sh 3 1
and the second process will terminate first. In either case, one can see that this operates as desired.