wait命令 shell

转自:http://nanxiao.me/bash-shell-wait/ 

      http://man.linuxde.net/wait

wait命令用来等待指令的指令,直到其执行完毕后返回终端。该指令常用于shell脚本编程中,待指定的指令执行完成后,才会继续执行后面的任务。该指令等待作业时,在作业标识号前必须添加备份号"%"。


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命令。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值