Subshells and option inheritance
A subshell is a separate shell execution context derived from the current shell. Parenthesized groups and ordinary $(...) substitutions use subshell environments; the latter capture stdout and remove trailing newlines. Changes to ordinary variables, working directory and shell options inside such a context do not update the parent. BASH_SUBSHELL increases for nested subshell environments; unlike $$, BASHPID identifies the actual Bash process in these fixtures. A newly invoked Bash is not simply a copy of all shell variables; exported values cross the environment boundary. SHELLOPTS and BASHOPTS are readonly lists of enabled set and shopt options; exporting them can affect compatible child Bash startup. Do not export them casually. In non-POSIX mode, ordinary command substitution normally clears errexit (-e), unless inherit_errexit is enabled. POSIX mode enables that option. The many exceptions to errexit are deferred to Chapter 16. Test explicit statuses rather than relying solely on -e. Process substitution produces a path-like handle, not captured text; its producer status is not automatically the consumer status. A plain exported scalar crosses a new Bash process boundary; a nonexported scalar can still be visible in a parenthesized subshell. Neither environment copies ordinary variable assignments back into its parent.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Inspect subshell nesting
printf '%s\n' "$BASH_SUBSHELL"( printf '%s\n' "$BASH_SUBSHELL"; ( printf '%s\n' "$BASH_SUBSHELL" ) )printf '%s\n' "$BASH_SUBSHELL"Expected stdout:
0120The outer shell stays at depth zero in this script.
Isolate an option
set +o pipefail( set -o pipefail; if [[ -o pipefail ]]; then printf 'inner on\n'; fi )if [[ ! -o pipefail ]]; then printf 'outer off\n'; fiExpected stdout:
inner onouter offThe inner option change does not propagate back.
Compare errexit inheritance
bash -c 'set -e; shopt -u inherit_errexit; v=$(false; printf survived); printf "%s\n" "$v"'bash -c 'set -e; shopt -s inherit_errexit; v=$(false; printf unreachable); printf "%s\n" "$v"'printf 'inherited status=%s\n' "$?"Expected stdout:
survivedinherited status=1The second child exits after the failed assignment; the outer test shell has no errexit. These are deliberately unguarded commands inside each child.
Common mistakes
A subshell is not a security sandbox. Its file writes remain visible. A new bash -c and a parenthesized group have different inheritance rules.
Practice
Predict the nesting depth of two parentheses groups and check whether an option changed in the inner group affects the outer shell. Compare command substitution with and without inherit_errexit in separate child scripts.
Next: Coprocess communication preview