bash 脚本可以同时运行命令然后等待它们完成吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8993655/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:33:59  来源:igfitidea点击:

Can a bash script run simultaneous commands then wait for them to complete?

bash

提问by Colin

I want to write a bash script where I run two commands simultaneously, then continue when they both complete.

我想编写一个 bash 脚本,在其中同时运行两个命令,然后在它们都完成后继续。

Here's something that doesn't work, but I'll put it here to illustrate what I'm trying to do:

这里有一些不起作用的东西,但我会把它放在这里来说明我正在尝试做的事情:

#!/bin/bash
./job1 &
./job2
./dostuffwithresults

The script will run both job1 and job2 at the same time, but will only wait for job2 to finish before continuing. If job1 takes longer, then the results might not be ready for the final command.

该脚本将同时运行 job1 和 job2,但在继续之前只会等待 job2 完成。如果 job1 需要更长的时间,则结果可能无法用于最终命令。

回答by Michael Krelin - hacker

j1 &
j2 &
j3 &
wait $(jobs -p)
dostuffwithresults

回答by Harry Forbess

something like this should work

这样的事情应该工作

    #!/bin/bash
    while [ `pgrep job*` ]
    do 
    echo 'waiting'
    done

    ./dostuffwithresults