bhylu.com

Advertisements

Bash Subshells and Command Substitution

Make variable and directory lifetime visible.

How it works

Parentheses run a command group in a subshell environment. Changes to its variables or working directory do not normally change the parent shell. Command substitution also captures output from a separate execution environment and removes trailing newline characters. These boundaries help contain temporary work, but can surprise code expecting a loop or helper to update its caller’s state.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

subshells.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
desk_state=original
( desk_state=changed; [[ $desk_state == changed ]] ) || exit 1
[[ $desk_state == original ]] || exit 1
value=$(printf "north\n\n")
[[ $value == north ]] || exit 1
printf "Parent state retained; trailing newlines removed\n"

Expected result

Parent state retained; trailing newlines removed

The nested group sees its own changed value while the parent keeps original. The captured output illustrates newline removal, which matters when exact text bytes are part of a format. Avoid command substitution for binary streams or very large files; use files or pipelines with explicit status handling instead.

Primary technical reference: Bash documentation.