How do you run multiple programs in parallel from a bash script?
How about:
prog1 & prog2 && fg
This will:
- Start
prog1
. - Send it to background, but keep printing its output.
- Start
prog2
, and keep it in foreground, so you can close it withctrl-c
. - When you close
prog2
, you'll return toprog1
's foreground, so you can also close it withctrl-c
.
To run multiple programs in parallel:
prog1 &prog2 &
If you need your script to wait for the programs to finish, you can add:
wait
at the point where you want the script to wait for them.
If you want to be able to easily run and kill multiple process with ctrl-c
, this is my favorite method: spawn multiple background processes in a (…)
subshell, and trap SIGINT
to execute kill 0
, which will kill everything spawned in the subshell group:
(trap 'kill 0' SIGINT; prog1 & prog2 & prog3)
You can have complex process execution structures, and everything will close with a single ctrl-c
(just make sure the last process is run in the foreground, i.e., don't include a &
after prog1.3
):
(trap 'kill 0' SIGINT; prog1.1 && prog1.2 & (prog2.1 | prog2.2 || prog2.3) & prog1.3)