如何在后台执行多个 bash 函数但等待输出?

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

How do you execute several bash functions in the background but wait for output?

bashparallel-processing

提问by Kevin

I am trying to make a bash function to execute several web scrapes (using curl and such), and I want to have them all execute concurrently in the background, and all print their output to stdin. How is this possible?

我正在尝试制作一个 bash 函数来执行多个网页抓取(使用 curl 等),并且我想让它们都在后台同时执行,并且都将它们的输出打印到标准输入。这怎么可能?

回答by TrueY

It is an easy one! You can use &for this even for bashfunctions:

这是一个简单的!您&甚至可以将其用于bash函数:

#!/usr/bin/bash

x() { echo ==Solaris; sleep 1; echo ==East; sleep 1; echo ==Panta Rhei;}

x one&
x two&

echo Syrius; sleep 1
echo After Crying 

Output:

输出:

=one=Solaris
Syrius
=two=Solaris
=one=East
=two=East
After Crying

Press ENTER or type command to continue
=one=Panta Rhei
=two=Panta Rhei

So xis running in the background and prints to stdout. The Press ENTER or type command to continuewas presented by vim(as I started the script from vim) and shows that the background xprocess finishes its job after the main script finished. If You want to wait until all the background processes finish You can use the $!to get the PID of the background processes and the built-in wait <PID>as a last function.

所以x在后台运行并打印到stdout. 在Press ENTER or type command to continue被提出的VIM(我开始从脚本VIM),并显示该背景x的主脚本完成后,过程完成其工作。如果您想等到所有后台进程完成,您可以使用$!来获取后台进程的 PID,并将内置wait <PID>作为最后一个函数。

回答by Kevin

For anyone else who comes along:

对于其他任何人:

Given the following:

鉴于以下情况:

function par() {
    parallel sh -c ::: "sleep 1" "sleep 1" "sleep 1"
}

function seq() {
    sleep 1
    sleep 1
    sleep 1
}

Timing both commands shows that the first function executes all at once while the second function waits for each command to be finished before moving on to the next:

对这两个命令进行计时显示,第一个函数同时执行,而第二个函数在继续执行下一个命令之前等待每个命令完成:

$ time par && time seq

real    0m1.215s
user    0m0.147s
sys     0m0.085s

real    0m3.028s
user    0m0.011s
sys     0m0.012s

Happiness!

幸福!