如果任何命令失败,与退出失败并行运行命令 [英] run commands in parallel with exit fail if any command fails
问题描述
需要 bash 脚本方面的帮助.目标是:- 并行运行多个命令- 如果任何命令返回非零退出状态,则退出 1
Need help in a bash script. The goal is: - Run several commands in parallel - Exit 1 if any command return not-zero exit status
即
使用中间命令运行有错误:
Run with middle command has error:
$ ./parallel_commands "echo 1" "_echo 2" "echo 3" && echo "OK"
1
3
./parallel_commands: line 4: _echo: command not found
OK <- Incorrect
运行所有命令都有错误:
Run with all commands have errors:
$ ./parallel_commands "_echo 1" "_echo 2" "_echo 3" && echo "OK"
./parallel_commands: line 4: _echo: command not found
./parallel_commands: line 4: _echo: command not found
./parallel_commands: line 4: _echo: command not found
-> Result is fail -> Correct
Bash 脚本:
#!/bin/bash
for cmd in "$@"; do {
$cmd & pid=$!
PID_LIST+=" $pid";
} done
trap "kill $PID_LIST" SIGINT
wait $PID_LIST
谢谢.
推荐答案
您可能正在使用 GNU Parallel 寻找类似的东西:
You are probably looking for something like this using GNU Parallel:
parallel ::: "echo 1" "_echo 2" "echo 3" && echo OK
GNU Parallel 是一个通用的并行器,可以轻松地在同一台机器或您可以通过 ssh 访问的多台机器上并行运行作业.
GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.
如果您想在 4 个 CPU 上运行 32 个不同的作业,一个直接的并行化方法是在每个 CPU 上运行 8 个作业:
If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:
GNU Parallel 会在完成后生成一个新进程 - 保持 CPU 处于活动状态,从而节省时间:
GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:
安装
如果没有为您的发行版打包 GNU Parallel,您可以进行个人安装,这不需要 root 访问权限.这样做可以在 10 秒内完成:
If GNU Parallel is not packaged for your distribution, you can do a personal installation, which does not require root access. It can be done in 10 seconds by doing this:
(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash
其他安装选项见http://git.savannah.gnu.org/cgit/parallel.git/tree/README
了解详情
查看更多示例:http://www.gnu.org/software/parallel/man.html
观看介绍视频:https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1
浏览教程:http://www.gnu.org/software/parallel/parallel_tutorial.html
注册电子邮件列表以获得支持:https://lists.gnu.org/邮递员/列表信息/并行
Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel
这篇关于如果任何命令失败,与退出失败并行运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!