You can use the wait
built-in command available in Bash and in some other shells.
(see equivalent WAITFOR command on Windows)
Wait for the completion of each specified process and return its completion status.
Syntax wait [n ...] Key n A process ID or a job specification
Each n
can be a process identifier or job specification; if work specification is given, all processes in this working pipeline were waiting.
If n
is not given, all currently active child processes are waiting for, and the return status is zero.
If n
indicates a non-existent process or job, status 127
returned. Otherwise, the return status is the exit status of the last process or expected job.
A simple solution
Below, wait
waits indefinitely to complete all active active processes at the moment (i.e., in this case, three scripts).
./script1 & ./script2 & ./script3 & wait
Store PID in local shell variables
./script1 & pid1=$! ./script2 & pid2=$! ./script3 & pid3=$! wait $pid1 $pid2 $pid3
Save PID in temporary files
./script1 & echo $! >1.pid ./script2 & echo $! >2.pid ./script3 & echo $! >3.pid wait $(<1.pid) $(<2.pid) $(<3.pid) rm 1.pid 2.pid 3.pid
This last solution pollutes the current directory with three files ( 1.pid
, 2.pid
and 3.pid
). One of these files may be corrupted before the wait
call. Moreover, these files can be left in the file system in case of failure.
source share