Skip to main content
Command substitution with $(…) captures the output of commands into a variable, but it does so by spawning a subshell—a child process separate from your main shell:
Assignments made inside the subshell do not affect variables in the parent shell.
Because a new process is created, there’s a small performance cost compared to running commands directly in the parent shell.
Overusing complex command substitutions inside tight loops can degrade script performance. Measure and optimize if needed.
The image explains that a subshell is a child process spawned by a parent shell, inheriting environment variables but not propagating them back to the parent shell.

1. Subshell Syntax

Wrap commands in parentheses to run them in a subshell:
The image illustrates subshell syntax, showing a command enclosed in parentheses, with a note about script execution context.
To prove isolation:

2. Command Substitution with a Subshell

Combine a subshell with $(…) to capture its output separately from the parent shell:
Errors inside the subshell still appear on the terminal:

3. Command Layout in Subshells

Within parentheses, you can:
  • Put commands on separate lines
  • Separate with semicolons (;)
  • Pipe between them (|)
  • Chain with && or ||
The image explains the use of the OR operator || in subshell scenarios, showing a syntax example: (command1 || command2).

4. Common Subshell Scenarios

4.1 One-Liners to Change Directory Temporarily

Run commands in a different folder without affecting your current directory:
The image is a slide titled "Subshell – common scenarios," highlighting the use of a subshell to run commands without changing directories.
Interactive example:

4.2 Jenkins Pipeline Steps

In Jenkins Pipelines, each sh step executes in its own subshell. This isolation explains differences when scripts run in CI/CD environments.

5. Verifying Process IDs

Use $$ and $BASHPID to compare parent and subshell PIDs:

6. Propagating Values Back to the Parent Shell

Since subshells can’t modify parent variables directly, use a temporary file or another IPC mechanism:
This pattern is useful in scripts, loops, and CI/CD jobs when you need to retrieve data from a subshell.

Watch Video