0

I want to run some scripts in parallel and if all succeeds I will execute some extra commands. However if any of the subshells fails I want to exit immediately.

I guess it is easier to explain with an example:

exit_in_1() {
  sleep 1
  echo "This should be the last thing printed"
  exit 1
}

exit_in_2() {
  sleep 2
  echo "This should not be printed"
  exit 1
}

exit_in_1 &
exit_in_2 &

echo "This should be printed immediately"

sleep 3

echo "This should not be printed also"

Above script prints all the echos.

Mehmet Ataş
  • 10,447
  • 5
  • 46
  • 74
  • 3
    https://stackoverflow.com/a/1570356/612920 – Mansuro May 05 '18 at 19:24
  • 2
    Possible duplicate of [Get exit code of a background process](https://stackoverflow.com/questions/1570262/get-exit-code-of-a-background-process) – codeforester May 05 '18 at 20:39
  • I would not call this question a duplicate. Yes the other questions has the answer already however the question is different. I did not know that I need to check the exit code of background process to fail the main process. Anyone like me can benefit from this question. Note that what makes a question duplicate is that the question itself not the answer. – Mehmet Ataş May 05 '18 at 23:20

1 Answers1

1

Thanks to @Mansuro's comment I solved my problem like this:

exit_later() {
  sleep $1
  echo "This should be printed twice"
  exit $(($1-1))
}

pids=""
for i in {1..10}; do
  exit_later $i &
  pids+=" $!"
done

echo "This should be printed immediately"

for p in $pids; do
  if ! wait $p; then
    kill $pids
    exit 1
  fi
done

echo "This should not be printed"
Mehmet Ataş
  • 10,447
  • 5
  • 46
  • 74