Source From Here
QuestionI am writing a script, but there is something I need that I can't find a way to do it...
I need to make a command in the background "command1 &" and then somewhere in the script I need to wait for it to finish before I do command2. Basically, I need this:
- a=1
- while [$a -lt 4 ]
- . command1 &
- #Generates 1 Process
- a= `export $a +1`
- done
- #Wait until the 4 process end and then run the command2
- . command2
HowTo
You can use the command wait PID to wait for a process to end; You can also retrieve the PID of the last command with $!
In your case, something like this would work:
- test.sh
- #!/bin/sh
- L=1
- PID_LIST=""
- while [ $L -lt 4 ]
- do
- sleep 10 && echo "Loop-$L" &
- PID=$!
- PID_LIST="$PID_LIST $PID"
- L=$((L+1))
- done
- echo "Wait for all command1 to be completed..."
- wait $PID_LIST
- echo "All done!"
Supplement
* Bash shell script – while 迴圈
* How to Increment and Decrement Variable in Bash (Counter)
沒有留言:
張貼留言