Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: Run multiple command in background, store output in variable

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?

like image 424
Adam Matan Avatar asked Oct 14 '13 11:10

Adam Matan


1 Answers

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)"
like image 72
devnull Avatar answered Sep 25 '22 13:09

devnull