Saturday, February 9, 2013

shell script to block main script exit before all other spined backend script exit.

Sometimes, we need to write shell script to spin multiple process running parallel. Also, we want to wait all parallel process finish before we can process to next step. How to achieve this? Below is a simple Bash shell sample script to do this.

n=10
for ((i=1; i < $n; i++));
 do
 #compose the command
 realCmd="nohup yourCmdWithArguments >/dev/null 2>&1 &"
 #excute the command
 eval $realCmd
 #store command pid in an array.
  pidArray[$i]=$!
done

#wait for each process to be done
for ((i=1;i<$n;i++));
 do
   wait ${pidArray[$i]}
done

#continue to do next step that depends on results of all nohup spin processes above.

No comments:

Post a Comment