Wait for a process to finish

Biswajyoti Das picture Biswajyoti Das · Jun 29, 2009 · Viewed 165.8k times · Source

Is there any builtin feature in Bash to wait for a process to finish?

The wait command only allows one to wait for child processes to finish. I would like to know if there is any way to wait for any process to finish before proceeding in any script.

A mechanical way to do this is as follows but I would like to know if there is any builtin feature in Bash.

while ps -p `cat $PID_FILE` > /dev/null; do sleep 1; done

Answer

Rauno Palosaari picture Rauno Palosaari · Jan 12, 2017

To wait for any process to finish

Linux:

tail --pid=$pid -f /dev/null

Darwin (requires that $pid has open files):

lsof -p $pid +r 1 &>/dev/null

With timeout (seconds)

Linux:

timeout $timeout tail --pid=$pid -f /dev/null

Darwin (requires that $pid has open files):

lsof -p $pid +r 1m%s -t | grep -qm1 $(date -v+${timeout}S +%s 2>/dev/null || echo INF)