Shell 脚本等待后台命令

Joa*_*cau 14 shell scripting background-process

我正在写一个脚本,但我需要一些东西,但我找不到方法来做到这一点......

我需要在后台“command1 &”中创建一个命令,然后在脚本中的某个地方我需要等待它完成,然后再执行 command2。基本上,我需要这个:

注意:每个命令都在特定目录中运行!在 while 循环结束时,我的 command1 创建了 4 个目录,其中每个目录运行特定进程,因此运行的进程总数为 4

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
Run Code Online (Sandbox Code Playgroud)

我已经看到有关wait带有 pid 进程号的命令的内容,但这也不起作用。

Lau*_* C. 24

您可以使用该命令wait PID等待进程结束。

您还可以使用以下命令检索最后一个命令的 PID $!

在你的情况下,这样的事情会起作用:

command1 & #run command1 in background
PID=$! #catch the last PID, here from command1
command2 #run command2 while command1 is running in background
wait $PID #wait for command1, in background, to end
command3 #execute once command1 ended
Run Code Online (Sandbox Code Playgroud)

根据您的编辑,由于您有多个 PID 并且您知道它们,您可以这样做:

command1 & #run command1 in background
PID1=xxxxx
PID2=yyyyy
PID3=xxyyy
PID4=yyxxx
command2 #run command2 while command1 is running in background
wait $PID1 $PID2 $PID3 $PID4 #wait for the four processes of command1, in background, to end
command3 #execute once command1 ended
Run Code Online (Sandbox Code Playgroud)


ter*_*don 5

最干净的方法是让您comamnd1返回已启动进程的 PID,并wait按照 @LaurentC's答案的建议在每个进程上使用。

另一种方法是这样的:

## Create a log file
logfile=$(mktemp)

## Run your command and have it print into the log file
## when it's finsihed.
command1 && echo 1 > $logfile &

## Wait for it. The [ ! -s $logfile ] is true while the file is 
## empty. The -s means "check that the file is NOT empty" so ! -s
## means the opposite, check that the file IS empty. So, since
## the command above will print into the file as soon as it's finished
## this loop will run as long as  the previous command si runnning.
while [ ! -s $logfile ]; do sleep 1; done

## continue
command2
Run Code Online (Sandbox Code Playgroud)