2021年2月18日 星期四

[Linux 常見問題] Shell script wait for background command

 Source From Here

Question
I 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:
  1. a=1  
  2.   
  3. while [$a -lt 4 ]  
  4.   
  5.      . command1 &  
  6.    #Generates 1 Process    
  7.   
  8.      a= `export $a +1`  
  9. done  
  10.   
  11.    #Wait until the 4 process end and then run the command2   
  12.     . command2  
I've seen something about a wait command with the pid process number, but that didn't work also.

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
  1. #!/bin/sh  
  2. L=1  
  3. PID_LIST=""  
  4. while [ $L -lt 4 ]  
  5. do  
  6.     sleep 10 && echo "Loop-$L" &  
  7.     PID=$!  
  8.     PID_LIST="$PID_LIST $PID"  
  9.     L=$((L+1))  
  10. done  
  11.   
  12. echo "Wait for all command1 to be completed..."  
  13. wait $PID_LIST  
  14. echo "All done!"  
Execution result:
# ./test.sh
Wait for all command1 to be completed...
Loop-1
Loop-2
Loop-3
All done!

Supplement
Bash shell script – while 迴圈
How to Increment and Decrement Variable in Bash (Counter)

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...