0
votes

suppose I am running two commands in parallel in shell script, example below

/cmd1 &  
pid1=$!

/cmd2 &  
pid2=$!

status1=    # what should go here?

status2=$?  # I know this will have status of previous background process only

I want to proceed only if both the commands have clean exit status How do I check the status of first background process.

2

2 Answers

0
votes

How about this sir

monitor ()
{
  if ! $*
  then
    > error
  fi
}

clean()
{
  rm -f error
}

clean
monitor cmd1 &
monitor cmd2

if [ -a error ]
then
  echo error encountered
  exit
fi
0
votes

One solution is to use GNU Parallel with --joblog, here shown with the 2 commands exit 0 and exit 1:

(echo exit 0; echo exit 1) | parallel --joblog /tmp/foo
cat /tmp/foo
Seq     Host    Starttime       Runtime Send    Receive Exitval Signal  Command
1       :       1359451838.09   0.002   0       0       0       0       true
2       :       1359451838.093  0.002   0       0       1       0       false

The Exitval column will give the exit value. Also GNU Parallel will return non-zero if one of the jobs failed:

(echo exit 0; echo exit 1) | parallel && echo Do this if none fail

Or equivalent:

parallel ::: "exit 0" "exit 1" && echo Do this if none fail

Learn more