Skip to content
shellhacks.dev
Automation

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.

1 min read
Summarize in AI

You need to block until a process ends, and it may not be a child of your script.

Shell
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"
Text
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 gone

wait 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.

Share

More snippets

Automation

Wait for a File to Appear in a Bash Script

Wait for a file with an until loop on test -e, and have the writer create it under a temporary name and rename it, so the reader never sees half of it.

2 min read
Automation

Wait for a TCP Port to Open in a Bash Script

Wait until a TCP port accepts connections with a Bash loop that opens /dev/tcp/host/port, with no nc needed. It returns 0 once open, or 1 after the tries run out.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.