How can I run two commands in parallel and terminate them if ONE of them terminates with exit code 0?

5,873

Solution 1

Something like this:

(cmd1; [ "$?" -lt 2 ] && kill "$$") &
(cmd2; [ "$?" -lt 2 ] && kill "$$") &
wait

Solution 2

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.

Share:
5,873

Related videos on Youtube

Sam
Author by

Sam

Updated on September 18, 2022

Comments

  • Sam
    Sam almost 2 years

    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
    
    • xhienne
      xhienne over 7 years
      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.
    • Kusalananda
      Kusalananda over 7 years
      Also, in the title you say "exit code 0", but in the text you say "0 or 1".
  • xhienne
    xhienne over 7 years
    Well, you are terminating the parent along with the child processes. According to the title, it seems the parent script should survive its children.
  • ctrl-d
    ctrl-d over 7 years
    But it doesn't matter, OP is gone.