Linux – Bash background process still blocking script flow in subshell

bashlinuxscript

I am trying to do something that involves scripts calling other scripts in subshells to capture their output.

One of the scripts needs to have a side effect of starting a background process. This all works when executed directly, but it blocks when called within a subshell.

As a self-contained example consider the following 2 scripts:

test1.sh

#!/bin/bash
echo $(./test2.sh)

test2.sh

#!/bin/bash
(yes > /dev/null ; echo 'yes killed') &
echo success

When I run test2.sh by itself, I get the expected result of "success" on the terminal, and yes running in the background. Killing yes prints "yes killed" to the terminal as expected.
When I run test1.sh I expect to get the same behavior, but what actually happens is that the terminal hangs until I kill yes after which "success yes killed" is printed to the terminal.

What do I change to these scripts so that I can get the same behavior from calling either one?

The premise here is that the subshell evaluation in test1.sh will actually be stored in a variable for later use. The background process started in test2.sh should live past the execution of either script.

Best Answer

Command substitution $(...) turns output into arguments. It first needs the whole output, because it's not possibly to supply arguments dynamically one by one.

Related Question