Bash shell
内置了wait
命令,官方文档对wait
解释如下:
wait
wait [-n] [jobspec or pid …]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If the -n option is supplied, wait waits for any job to terminate and returns its exit status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
wait
命令可以使当前shell
进程挂起,等待所指定的由当前shell
产生的子进程退出后,wait
命令才返回。wait
命令的参数可以是进程ID
或是job specification
。举例如下:
root# sleep 10 &
[3] 876
root# wait 876
[3]+ Done sleep 10
root# sleep 20 &
[1] 877
root# wait %1
[1]+ Done sleep 20
wait
命令一个很重要用途就是在Bash shell
的并行编程中,可以在Bash shell
脚本中启动多个后台进程(使用&
),然后调用wait
命令,等待所有后台进程都运行完毕,Bash shell
脚本再继续向下执行。像下面这样:
command1 &
command2 &
wait
Bash shell
还有一个内置变量:$!
,用来记录最后一个被创建的后台进程。
root# sleep 20 &
[1] 874
root# sleep 10 &
[2] 875
root# echo $!
875
echo $!
输出结果是875
,是第二个执行的sleep
命令。
参考资料:
Does bash script wait for one process to finish before executing another?。
我测试了下,很好用,完美解决问题,谢谢
for i in {1..10}
do
echo $i
sleep 15s &
echo $i
sleep 20s &
echo $i
wait
echo $i
done