我有一个bash脚本,我在其中调用其他脚本以并行运行。使用wait命令,我可以一直等到所有并行进程完成。但我想知道在后台并行执行的所有进程是否都成功执行(返回代码为0)。
我的代码看起来像这样:
--calling multiple processes to execute in backgroud
process-1 &
process-2 &
process-3 &
wait
--after parallel execution finishes I want to know if all of them were successful and returned '0'发布于 2016-03-19 04:27:43
您可以使用wait -n,它返回终止的下一个作业的退出代码。为每个后台进程调用一次。
process-1 &
process-2 &
process-3 &
wait -n && wait -n && wait -n发布于 2016-03-19 06:31:37
wait -n似乎是正确的解决方案,但是由于bash 4.2.37中没有它,您可以尝试这个技巧:
#!/bin/bash
(
process-1 || echo $! failed &
process-2 || echo $! failed &
process-2 || echo $! failed &
wait
) | grep -q failed
if [ $? -eq 0 ]; then
echo at least one process failed
else
echo all processes finished successfully
fi只需确保在获得实际成功时,进程本身不会返回字符串"failed“。您还可以使用stdin和stderr运行进程,并使用process-1 &>/dev/null重定向do /dev/null
发布于 2018-01-12 11:12:11
我已经编写了一个工具来稍微简化解决方案:https://github.com/wagoodman/bashful
你提供一个文件来描述你想要运行的东西...
# awesome.yaml
tasks:
- name: My awesome tasks
parallel-tasks:
- cmd: ./some-script-1.sh
- cmd: ./some-script-2.sh
- cmd: ./some-script-3.sh
- cmd: ./some-script-4.sh...and像这样运行它:
bashful run awesome.yaml然后,它将与显示每个任务状态的垂直进度条并行运行您的任务。失败以红色表示,如果发现任何错误,程序将以1退出(在并行块完成后退出)。
https://stackoverflow.com/questions/36093404
复制相似问题