We want to run some process in the background and continue script execution. Then at some point we want to stop and wait for this process to finish. We also want to capture the exit code of this process. Once we have PID of the process we put in background, wait function is all we need. It will return the exit code of the process it waited for, even if the process has finished its execution before wait function was called.

#!/usr/bin/env bash

# start sleep process in background
echo Starting sleep
(sleep 5; exit 3) &
# get the pid of the last process run

echo Processing...
sleep 10
echo "sleep must be done by now"
ps aux | grep sleep

# wait for the process to finish
echo Waiting for sleep to finish
wait $pid
echo "Sleep finished with exit code $?"
echo done