5

I have 2 commands which are to be run simultaneously. And I want the script to terminate if one of them either exits with code 0 or 1. How can I achieve this in Linux(Ubuntu)

cmd1 &
cmd2 &
wait
  • 1
    What must happen to the parent script? The title say you want to terminate the child processes as soon as one ends, but in the body of your post, you want the (parent?) script to terminate. – xhienne Jan 10 '17 at 22:45
  • Also, in the title you say "exit code 0", but in the text you say "0 or 1". – Kusalananda Jan 11 '17 at 10:25
6

Something like this:

(cmd1; [ "$?" -lt 2 ] && kill "$$") &
(cmd2; [ "$?" -lt 2 ] && kill "$$") &
wait
  • 1
    updated, didn't see that requirement – ctrl-d Jan 10 '17 at 22:19
  • Well, you are terminating the parent along with the child processes. According to the title, it seems the parent script should survive its children. – xhienne Jan 10 '17 at 22:33
  • 2
    But it doesn't matter, OP is gone. – ctrl-d Jan 10 '17 at 23:01
1

With bash 4.4 and newer:

cmd1 & p1=$!
cmd2 & p2=$!

wait -n
[ "$?" -gt 1 ] || kill "$p1" "$p2"
wait

wait -n waits for the first background job to finish and reports its exit status in $?.

That's assuming you want to kill the other job when the first one exits with 0 or 1. Change the kill command to exit if you want to exit the script and leave the other command running unparented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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