04. Executing Shell Command
What is a Subshell?¶
A subshell is a separate shell process spawned by the current shell to execute a command. The output produced by that command can then be captured and used elsewhere in the script.
Command substitution allows Bash to:
-
Execute a command
-
Capture its output
-
Replace the command with its result
Syntax¶
The command inside $( ) runs in a subshell, and its output replaces the entire expression.
Example Script¶
subshell.sh¶
#!/bin/bash
# 04. Executing Shell Command
echo $(uname -o)
# executing bash command without subshell
echo uname -o
Execution¶
Running the command directly¶
Running the script¶
Explanation¶
1. Using Subshell $(uname -o)¶
Step-by-step:
-
Bash creates a subshell.
-
The command
uname -oruns inside it. -
The output (
GNU/Linux) is captured. -
The captured output replaces
$(uname -o). -
echoprints the result.
Effectively Bash interprets it as:
2. Without Subshell¶
Here:
-
No command execution happens.
-
Bash treats
uname -oas plain text. -
The text is printed literally.
Output:
Key Difference¶
| Command | Behavior | Result |
|---|---|---|
echo $(uname -o) |
Executes command in subshell | Prints command output |
echo uname -o |
Treated as text | Prints literal string |
Why Use Command Substitution?¶
Command substitution is useful when you need to:
-
Store command output in variables
-
Combine commands
-
Automate workflows
-
Dynamically generate values
Example:
Output:
Old vs Modern Syntax¶
Older Bash used backticks:
Modern recommended syntax:
Reasons to prefer $( ):
-
More readable
-
Easier nesting
-
Less error-prone
Nested Command Example¶
Bash evaluates from the innermost command outward.
Summary¶
-
$( )performs command substitution using a subshell. -
The command runs and its output replaces the expression.
-
Without
$( ), text is printed literally. -
Modern Bash scripts should always prefer
$( )over backticks.
This mechanism is fundamental for writing dynamic and automated Bash scripts.