Bash & (&) 运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9258387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash & (ampersand) operator
提问by Misha Moroshko
I'm trying to run 3 commands in parallel in bash shell:
我正在尝试在 bash shell 中并行运行 3 个命令:
$ (first command) & (second command) & (third command) & wait
The problem with this is that if first command
fails, for example, the exit code is 0
(I guess because wait
succeeds).
问题在于,如果first command
失败,例如,退出代码是0
(我猜是因为wait
成功)。
The desired behavior is that if one of the commands fails, the exit code will be non-zero (and ideally, the other running commands will be stopped).
所需的行为是,如果其中一个命令失败,退出代码将为非零(理想情况下,其他正在运行的命令将被停止)。
How could I achieve this?
我怎么能做到这一点?
Please note that I want to run the commands in parallel!
请注意,我想并行运行这些命令!
采纳答案by Karoly Horvath
the best I can think of is:
我能想到的最好的是:
first & p1=$!
second & p2=$!
...
wait $p1 && wait $p2 && ..
or
或者
wait $p1 || ( kill $p2 $p3 && exit 1 )
...
however this still enforces an order for the check of processes, so if the third fails immediately you won't notice it until the first and second finishes.
但是,这仍然强制执行检查进程的命令,因此如果第三个立即失败,您在第一个和第二个完成之前不会注意到它。
回答by potong
This might work for you:
这可能对你有用:
parallel -j3 --halt 2 <list_of_commands.txt
This will run 3 commands in parallel.
这将并行运行 3 个命令。
If any running job fails it will kill the remaining running jobs and then stop, returning the exit code of the failing job.
如果任何正在运行的作业失败,它将杀死剩余的正在运行的作业,然后停止,返回失败作业的退出代码。
回答by anubhava
You should use &&
instead of &
. eg:
你应该使用&&
而不是&
. 例如:
first command && second command && third command && wait
However this will NOT run your command in parallel as every subsequent command's execution will depend on exit code 0 of the previous command.
但是,这不会并行运行您的命令,因为每个后续命令的执行都将取决于前一个命令的退出代码 0。