Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I try to make a shell script to launch a serie of long-runner processes. Let's call them a, b, c, d and e. Processes b, c and d should run in parallel, and process e must run after all of the previous ones have terminated successfully.

There is my (pseudo-)code :

    echo "starting a"
    (echo "starting b"; b; exit $?)&
    (echo "starting c"; c; exit $?)&
    (echo "starting d"; d; exit $?)&
    echo "starting e"

My problem is, if any of b, c, d fails, the script continues and executes e. Is there a way to prevent that?

Huge thanks for any answers !


share|improve this question
(echo "starting b"; b; exit $?) - the exit $? is definitely redundant. You can leave it off and the subshell will return exit code from b anyway. – Theodros Zelleke Aug 14 '12 at 9:13
Possible duplicate of… – jpe Aug 14 '12 at 9:14
    (echo "starting b"; b)&
    (echo "starting c"; c)&
    (echo "starting d"; d)&
    wait %1 && wait %2 && wait %3

when waiting for a specific job wait returns this jobs exit code

To Understand look at these two examples:
only the last line is important (shows exit status of wait)

(sleep 3; false) & wait; echo $?
[1] 25358
[1]+  Exit 1                  ( sleep 3; false )


(sleep 3; false) & wait %1; echo $?
[1] 25362
[1]+  Exit 1                  ( sleep 3; false )
share|improve this answer
This will wait for all processes to complete, but does not capture the ir exit status. – Henk Langeveld Aug 14 '12 at 12:45
@HenkLangeveld: I have updated my answer in response to your objection – Theodros Zelleke Aug 14 '12 at 13:16

By running a process in the background, you've basically told the shell that you're not interested in its success or failure.

wait will report the value of any signal in its exit code, if that applies. This is not what you're looking for.

A solution would be to have each command report its status to stdout and count the responses with grep.

  (echo "starting b"; b && echo ok)&
  (echo "starting c"; c && echo ok)&
  (echo "starting d"; d && echo ok)&
} | 
grep -c ok | ( read n && (( n==3 )) ) && 

echo "starting e"; e
share|improve this answer
In ksh93, grep -c ok | read n && (( n==3 )) && would work as well. – Henk Langeveld Aug 14 '12 at 9:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.