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ş
  • 11,081
  • 6
  • 51
  • 78
  • 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

2 Answers2

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ş
  • 11,081
  • 6
  • 51
  • 78
0

With GNU Parallel this might work:

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
}

export -f exit_in_1 exit_in_2

parallel --halt-on-error 2 ::: 'echo "This should be printed immediately"' exit_in_1 exit_in_2 || exit 1

echo "This should not be printed also"

Or:

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

echo "This should be printed immediately"

parallel -j0 --halt-on-error 2 exit_later ::: {1..10} || exit 1

echo "This should not be printed"
Ole Tange
  • 31,768
  • 5
  • 86
  • 104