1

I have a function foo which takes one argument and get result by some calculation.

foo(){
   # do some calculation 
   sleep 10s
   echo result
}

I need to execute a function several times. Each time of execution takes some time and is independent so I want to do this in parallel.

result1=$(foo arg1)&
result2=$(foo arg2)&
result3=$(foo arg3)&
result4=$(foo arg4)&

However, the result variables are empty after invoking the function. How can I get the result value correctly?

CodePurin
  • 183
  • 6
  • Going to need more details to help you with this mate, e.g. is the foo function inside a script? Can you provide some example input and output data? Would a tool like GNU parallel be a good solution to your problem (https://www.gnu.org/software/parallel/)? – jared_mamrot Apr 21 '20 at 02:54
  • @jpmam1 Thanks for your comment. The foo function is defined in shell script. Argument of foo function is name of network interface, and it will return the number of receiving packets in 10 sec. For example, `foo eth0` may return `1394`. I prefer to use shell command only. – CodePurin Apr 21 '20 at 03:36
  • what about `foo arg1 > /some/file &` and check the file afterwards? – pynexj Apr 21 '20 at 04:45
  • Without gnu parallel you could try using fifo pipes. Can you adapt this solution to solve your problem: https://stackoverflow.com/questions/37854393/how-to-assign-the-output-of-a-background-job-into-a-bash-variable ? – jared_mamrot Apr 21 '20 at 06:20

0 Answers0