2

This question follows from this one and one of its answers' recommendation to read Linuxtopia - Chapter 20. Subshells.

I'm a bit confused by this statement at the Linuxtopia site:

subshells let the script do parallel processing, in effect executing multiple subtasks simultaneously.
https://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/subshells.html

Does this mean that subshells, run from a script, are always run in parallel to the original script? Experimentally, this does not appear to be the case, but I'd be grateful for expert confirmation one way or the other.

#! /usr/bin/bash

# This script reliably prints:
# hello
# world
# 0
# ...implying that the the subshell is not run in parallel with this script.

(echo hello;
echo world)

echo $?

.

#! /usr/bin/bash

# This script prints:
# 0
# hello
# world
# ...implying that the the subshell is run in parallel with this script.

(echo hello;
echo world) &

echo $?

Is the use of & what the Linuxtopia site might have meant by "[letting] the script do parallel processing"?


Note: I'm familiar with the concept of suffixing commands with & in bash...it runs said command as a background process. So my question is more about whether command(s) executed in a subshell are run as background/parallel process by default, or if addition of the & here, as well, is what causes the background/parallel execution. The wording of the Linuxtopia article, to me, implied the former, which doesn't appear to match observation.

StoneThrow
  • 1,717

1 Answers1

2

Depends how you create the subshell.

( command ) will run command in a subshell and wait for the subshell to complete before continuing.

command & will run command in a subshell in the background. The shell will continue on to the next command without waiting for the subshell to finish. This may be used for parallel processing.

coproc command is similar to command &, but also establishes a two-way pipe between the main shell and the subshell.

jayhendren
  • 8,384
  • 2
  • 33
  • 58