How Command Substitution Works in Linux Scripts

Command substitution is a fundamental Linux shell scripting feature that executes a specified command and replaces the command text itself with the standard output of that execution. This article explains how command substitution works under the hood, the two main syntax forms available, practical scripting examples, and critical behaviors such as subshell isolation and word splitting.

The Underlying Mechanism

When a shell script encounters a command substitution, it performs the following steps:

  1. Subshell Creation: The shell spawns a subshell, which is an isolated child process of the current script.
  2. Execution: The command inside the substitution syntax executes within this child subshell.
  3. Capture: The standard output (stdout) of the executed command is captured, while standard error (stderr) is left untouched (and will print to the terminal unless redirected).
  4. Stripping Trailing Newlines: The shell automatically trims any trailing newline characters from the captured output.
  5. Replacement: The original command syntax in the script is replaced by the captured output string before the enclosing command runs.

Because the command runs in a subshell, any variables set, directory changes made (via cd), or environmental shifts created within the substitution do not persist in the parent script.

Syntax Options

Linux supports two distinct syntaxes for command substitution:

1. The Modern Syntax: $(command)

This is the standard POSIX syntax and the recommended approach for modern shell scripts.

current_user=$(whoami)
echo "Current user is: $current_user"

Advantages of $(command) include:

2. The Legacy Syntax: `command` (Backticks)

Backticks represent the traditional Unix/Bourne shell syntax.

current_user=`whoami`
echo "Current user is: $current_user"

While still supported for backward compatibility, backticks are generally discouraged because nesting requires cumbersome backslash escaping:

parent_dir=`dirname \`which bash\``

Common Use Cases

Critical Best Practices