4

Here's an example program:

#!/bin/bash

for x in {1..5}
do
  output[$x]=$(echo $x) &
done

wait

for x in {1..5}
do
  echo ${output[$x]}
done

I would expect this to run and print out the values assigned to each member of the output array, but it prints nothing. Removing the & correctly assigns the variables. Must I use different syntax to achieve this in parallel?

Jack
  • 2,153
  • 5
  • 28
  • 43

3 Answers3

4

This

output[$x]=$(echo $x) &

puts the whole assignment in a background task (sub-process) and that's why you're not seeing the result, since it's not propogated to the parent process.

You can use wait to wait for subprocesses, but returning results (other than status codes) is going to be difficult. Perhaps you can write intermediate results to a file, and collect those results after all processes have finished ? (not nice, I appreciate)

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

If you want to avoid writing files, you can use GNU parallel:

#!/bin/bash
output=(`parallel -k --gnu echo {1} ::: {1..5}`)
for i in ${output[@]}
do
   echo $i
done

The -k is to preserve the order of the output

user000001
  • 32,226
  • 12
  • 81
  • 108
0

Use parset from GNU Parallel:

#!/bin/bash

typeset -A output
parset output echo {} ::: {1..5}

for x in {1..5}
do
  echo ${output[$x]}
done
Ole Tange
  • 31,768
  • 5
  • 86
  • 104