How to handle async subshell exit
It is not related to the process being a background process, it is related to the exit status of the wait
command.
From help wait
:
If ID is not given, waits for all currently active child processes, and the return status is zero.
$ bash -exc '(sleep 1; exit 1) & wait ; echo done'
+ wait
+ sleep 1
+ exit 1
+ echo done
done
If the -n option is supplied, waits for the next job to terminate and returns its exit status.
$ bash -exc '(sleep 1; exit 1) & wait -n; echo $?:done'
+ wait -n
+ sleep 1
+ exit 1
Your code would not terminate the current shell session since no non-zero exit status is returned to it. The result in the calling shell of starting a background job is always zero.
If you had used wait "$!"
or wait -n
("wait for next job to finish"), then the shell session would have terminated since wait
would have returned the exit status of the job that it waited for, which is non-zero.
See help wait
in bash
.