2

I have two shell scripts say A and B. I need to run A in the background and run B in the foreground till A finishes its execution in the background. I need to repeat this process for couple of runs, hence once A finishes, I need to suspend current iteration and move to next iteration.

Rough idea is like this:

for((i=0; i< 10; i++))  
do  
./A.sh &

for ((c=0; c< C_MAX; c++))  
do  
./B.sh  
done

continue

done

how do I use 'wait' and 'continue' so that B runs as many times while A is in the background and the entire process moves to next iteration once A finishes

chown
  • 51,908
  • 16
  • 134
  • 170
marc
  • 949
  • 14
  • 33

2 Answers2

3

Use the PID of the current background process:

./A.sh &
while ps -p $! >/dev/null; do
    ./B.sh
done
thiton
  • 35,651
  • 4
  • 70
  • 100
  • Wil this remove the need for 'continue' and move to next iteration ? – marc Nov 04 '11 at 19:21
  • @thiton Nice stuff (+1). Please take a look at my answer. I believe it was asked a little different logic but your wait-continue while loop is really great. – ztank1013 Nov 04 '11 at 20:30
1

I am just translating your rough idea into bash scripting. The core idea to implement the wait-continue mechanism (while ps -p $A_PID >/dev/null; do...) is taken from @thiton who posted an answer earlier to your question.

for i in `seq 0 10`
do
  ./A.sh &
  A_PID=$!
  for i in `seq 0 $C_MAX`
  do
    ./B.sh
  done
  while ps -p $A_PID >/dev/null; do
      sleep 1
  done
done
ztank1013
  • 6,939
  • 2
  • 22
  • 20