0

So, in my script, I want to start two processes in the background, after this I want to wait for both to complete and I want to get the stdout of the processes in variables.

To run in background, I can use
command &

To get the result in a variable I can run the command within backquotes.

But when I do command & within backquotes, the whole thing becomes blocking.

So, how do I solve my problem?

Hashken
  • 4,396
  • 7
  • 35
  • 51

1 Answers1

4

Commands run in background run in a child process, and there is no way for a child process to modify a parameter (variable) in the parent process. So technically, what you're looking for is impossible.

However, you can store the child's stdout (and, if you wish, stderr) in a file; you'll just have to make sure to give the file a unique name. (See man mktemp, for example.) After you wait for the background process to finish, you can read the temporary file into a parameter, and delete the file.

tmp1=$(mktemp)
tmp2=$(mktemp)
command1 > "$tmp1" &
command2 > "$tmp2" &
wait
OUTPUT1=$( < "$tmp1" ) && rm "$tmp1"
OUTPUT2=$( < "$tmp2" ) && rm "$tmp2"
chepner
  • 497,756
  • 71
  • 530
  • 681
rici
  • 234,347
  • 28
  • 237
  • 341