假设我有以下 bash 脚本:
#!/usr/bin/env bash
process-1&
process-2&
process-3&
我有两个问题:
- 如何在脚本末尾检查所有进程是否以退出代码 0 退出?
- 我的脚本如何“等待”直到所有启动的进程完成,然后进行总结
echo
(也许通知用户退出代码)?
答案1
您可以使用内置的 bash wait
。
3次wait -n
,每次检查退出状态。
从man bash
:
wait [-n] [n ...]
Wait for each specified child process and return its termination
status. Each n may be a process ID or a job specification; if a
job spec is given, all processes in that job's pipeline are waited
for. If n is not 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 n specifies a non-existent process or job, the return
status is 127. Otherwise, the return status is the exit status of
the last process or job waited for.