How to execute several bash functions in the background, but wait for an exit?

I am trying to make a bash function to execute multiple web assemblies (using curl, etc.), and I want them all to run in the background at the same time, and all output to stdin. How is this possible?

+4
source share
2 answers

It is simple! You can use & for this even for the function:

 #!/usr/bin/bash x() { echo =$1=Solaris; sleep 1; echo =$1=East; sleep 1; echo =$1=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 x runs in the background and prints to stdout . Press ENTER or type command to continue was introduced by (as I started the script from ) and shows that the background process x exits after the main script has finished. If you want to wait until all background processes are complete, you can use $! to get the PID of the background processes and the built-in wait <PID> as the last function.

+8
source

For everyone who comes:

Given the following:

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

Timing to both commands shows that the first function performs everything at once, and the second function waits for each command to complete 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!

+2
source

Source: https://habr.com/ru/post/1488214/


All Articles