How do I run a sequence of commands in parallel, and store their output in a variable?
I've tried:
output=`(echo -n "started "; sleep 2; echo "stopped") &`
echo "output before=$output"
wait
echo "output after=$output"
And got a pause of two seconds, followed by:
output before=started stopped
output after=started stopped
I expected:
output before=
<2 seconds pause>
output after=started stopped
How do I run a sequence of commands in the background, and store their output in a variable?
From the manual:
If a command is terminated by the control operator
‘&’
, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true).
A workaround would be to store the output in a file and read from it. The following might work for you:
tempout=$(mktemp)
( echo -n "started "; sleep 2; echo "stopped" ) > "${tempout}" &
echo "output before=$(<$tempout)"
wait
echo "output after=$(<$tempout)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With