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
Best Answer
After some ruminations, I came up with an ugly workaround:
As requested in a comment, here is how to make this more extensible for an arbitrarily large list:
The resultant output will be in the
data
array.