Skip to main content
Command substitution is a fundamental feature of Bash scripting that lets you capture the output of one command and embed it into another. This technique improves script readability and enables dynamic data handling in your shell scripts.

Recap: Variable Expansion

Use $ followed by a variable name to expand its value. Enclose the name in curly braces {} to avoid ambiguity, and wrap expansions in quotes to prevent word splitting and globbing.
Always quote your variable expansions ("${var}") to preserve whitespace and avoid unexpected globbing.

What Is Command Substitution?

Command substitution runs a command in a subshell and replaces the command with its standard output. There are two syntaxes:

Example: Counting Files on the Command Line

Using $( ... )

Create command-substitution.sh:
Run it:

Using Backticks (Deprecated)

Backticks are deprecated. They complicate nesting and reduce readability. Always prefer $( ... ) in modern Bash scripts.

Accepting a Directory Argument

Require the user to specify a target directory:

Timing Considerations

Command substitution runs once when assigned. If you modify files later, the stored value stays unchanged until you reassign it.
Re-running the script updates the count:

Subshell Scope

Command substitution executes in a subshell. Variables modified inside do not affect the parent shell:
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.
A subshell inherits your environment but keeps its changes local.

Performance Considerations

Each command substitution spawns a new process. In most scripts this overhead is negligible, but in performance-critical loops, minimize unnecessary substitutions.
Avoid placing heavy command substitutions inside tight loops. Consider alternatives like readarray or built-in string operations when processing large datasets.

Honorable Mentions

Watch Video