Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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"
    a
}&&
{
    (echo "starting b"; b; exit $?)&
    (echo "starting c"; c; exit $?)&
    (echo "starting d"; d; exit $?)&
    wait
}&&
{
    echo "starting e"
    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 !

Antoine

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 stackoverflow.com/questions/356100/… –  jpe Aug 14 '12 at 9:14

2 Answers 2

{
    (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 )
0

--

(sleep 3; false) & wait %1; echo $?
[1] 25362
[1]+  Exit 1                  ( sleep 3; false )
1
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
1  
@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

 
discard

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.