Skip to content

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

$(command)

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

$ uname -o
GNU/Linux

Running the script

$ ./subshell.sh
GNU/Linux
uname -o

Explanation

1. Using Subshell $(uname -o)

echo $(uname -o)

Step-by-step:

  1. Bash creates a subshell.

  2. The command uname -o runs inside it.

  3. The output (GNU/Linux) is captured.

  4. The captured output replaces $(uname -o).

  5. echo prints the result.

Effectively Bash interprets it as:

echo GNU/Linux

2. Without Subshell

echo uname -o

Here:

  • No command execution happens.

  • Bash treats uname -o as plain text.

  • The text is printed literally.

Output:

uname -o

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:

os=$(uname -o)
echo "Operating System: $os"

Output:

Operating System: GNU/Linux

Old vs Modern Syntax

Older Bash used backticks:

echo `uname -o`

Modern recommended syntax:

echo $(uname -o)

Reasons to prefer $( ):

  • More readable

  • Easier nesting

  • Less error-prone


Nested Command Example

echo $(echo $(uname -o))

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.