0

This script works as it should:

#!/bin/bash
sleep 9 &
wait
echo "ok"

Return "OK" after aprox. 9 seconds.

But this one:

#!/bin/bash
echo "1" | while read in
do
sleep 9 &
done
wait
echo "ok"

Return "OK" immediately. What's wrong, why we didn't wait for background task? What is my error or misunderstanding?

Denis
  • 1
  • Do you use `bash` or another shell? – Cyrus Dec 06 '21 at 21:44
  • 3
    move the `wait` inside the `while/done` loop and you should get a 9-second wait (reason being that you're pushing the `wait` down into the subshell where the background process (`sleep 9 &`) is being invoked) – markp-fuso Dec 06 '21 at 21:51
  • 1
    Closely related (though about variables, not subprocesses): ["How to pipe input to a Bash while loop and preserve variables after loop ends"](https://stackoverflow.com/questions/19570413/how-to-pipe-input-to-a-bash-while-loop-and-preserve-variables-after-loop-ends) and [BashFAQ #24: "I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?"](https://mywiki.wooledge.org/BashFAQ/024) – Gordon Davisson Dec 06 '21 at 22:25
  • Thanks, I got answer (to use process substitution for example due to shell fork). – Denis Dec 06 '21 at 22:27

0 Answers0