Wait for a Process to Exit in a Bash Script
Wait for any process to finish with tail --pid=PID -f /dev/null. The wait builtin works only for children of the same shell and returns 127 for any other process.
You need to block until a process ends, and it may not be a child of your script.
sleep 3 &
pid=$!
( wait "$pid" ); echo "wait from a subshell: exit $?"
tail --pid="$pid" -f /dev/null
echo "tail returned after about ${SECONDS}s"
kill -0 "$pid" 2> /dev/null || echo "process $pid is gone"bash: line 3: wait: pid 1066 is not a child of this shell
wait from a subshell: exit 127
tail returned after about 3s
process 1066 is gonewait PID only knows the children of the current shell, so from a subshell it reports not a child of this shell and exits with status 127. GNU tail --pid=PID -f /dev/null follows nothing and returns as soon as the process has gone, whoever started it, and the run shows it returning after about three seconds. kill -0 PID then confirms that the process is gone, since signal 0 only checks that it exists. See tail invocation.
--pid is a GNU extension, so on other systems use a loop of kill -0 "$pid" with a short sleep. A PID can be reused after the process ends, so a long wait can in theory follow a different process. A zombie counts as alive until its parent collects it.