I'm trying to loop until a background process (launched earlier in the script) is complete. An easily reproducible test case is:
ping -c 10 localhost &>/dev/null &
On the command line, I can loop while [[ -n $(jobs) ]]
(while $(jobs)
is not null).
$ ping -c 10 localhost &>/dev/null &
[1] 19078
$ while [[ -n $(jobs) ]]; do echo -n .; sleep 1; done
.........[1]+ Done ping -c 5 localhost &> /dev/null
However, the same two lines in a script will keep printing .
s until I hit Ctrl-C
.
Weirdly, if I call jobs
inside the loop, the script ends as expected.
$ ./background-ping.sh
.[1]+ Running ping -c 5 localhost &> /dev/null &
.[1]+ Running ping -c 5 localhost &> /dev/null &
.[1]+ Running ping -c 5 localhost &> /dev/null &
.[1]+ Running ping -c 5 localhost &> /dev/null &
.[1]+ Done ping -c 5 localhost &> /dev/null
I am aware that there are other ways to check if the background job is complete (e.g. checking /proc
), but I want to know why checking jobs
doesn't work as expected.