I'm trying to set several environment variables with the results from command substitution. I want to run the commands in parallel with & and wait. What I've got currently looks something like
export foo=`somecommand bar` &
export fizz=`somecommand baz` &
export rick=`somecommand morty` &
wait
But apparently when using & variable assignments don't stick. So after the wait, all those variables are unassigned.
How can I assign these variables in parallel?
UPDATE: Here's what I ended up using based off the accepted answer
declare -a data
declare -a output
declare -a processes
var_names=(
foo
fizz
rick
)
for name in "${var_names[@]}"
do
processes+=("./get_me_a_value_for $name")
done
index=0
for process in "${processes[@]}"; do
output+=("$(mktemp)")
${process} > ${output[$index]} &
index=$((index+1))
done
wait
index=0
for out in "${output[@]}"; do
val="$(<"${out}")"
rm -f "${out}"
export ${var_names[index]}="$val"
index=$((index+1))
done
unset data
unset output
unset processes
bar,baz, andmortytake (say) ten seconds each to run, assigning the variables in parallel would take ten seconds, rather than thirty if run in series.foo=$( ( sleep 3, echo bar ) & )to work around the problem, but that just makes the assignment not return until the subshell has completed (which in retrospect makes sense).