Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Command Substitution

Direct answer

Command substitution $(command) runs a command and inserts its stdout into the command line, for example today=$(date +%F). The older backtick form does the same.

When to use this

Use it to capture a command's output in a variable or argument, or when a captured value is empty or split.

First 30 seconds

1. echo "$(cmd)" — expected output?

2. Empty → the command failed or wrote to stderr; run it alone.

3. Split into words → quote the substitution.

4. Check the exit code: out=$(cmd) || echo failed.

5. Use the variable.

Operational verification

subshell runs the command → stdout captured → trailing newlines removed → inserted (and split unless quoted)

Evidence · next step

For Shell & Bash → Command Substitution, continue with the first unproven Topic check: Quote command substitutions when the result is intended as one argument/value. If that boundary is healthy, advance to the adjacent check: Test empty output, embedded whitespace/newlines, wildcard characters and failing nested commands. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
linux
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformlinux
Scope / prerequisiteUse it to capture a command's output in a variable or argument, or when a captured value is empty or split.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

5 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Operational evidence path Verify boundary

outer parse → spawn subshell/nested command → nested stdout + status → strip trailing newlines → quote-dependent splitting/globbing → outer argv/value → downstream command

Healthy evidence: nested command status is handled, output normalization is expected, quoting yields intended arguments and downstream behavior is correct.

Step 2 Verification and output interpretation Verify boundary

Existing fast checks for this Topic. - Quote command substitutions when the result is intended as one argument/value.

  • Test empty output, embedded whitespace/newlines, wildcard characters and failing nested commands.
  • Capture status separately where nested failure must abort or alter logic.
  • Avoid using command substitution for binary/NUL-delimited data; verify final argv/value before downstream mutation.

Verification chain. outer parse → spawn subshell/nested command → nested stdout + status → strip trailing newlines → quote-dependent splitting/globbing → outer argv/value → downstream command

Step 3 Commands Verify boundary
today=$(date +%F)
echo "Kernel: $(uname -r)"
Step 4 Failure modes and next checks Narrow the fault

Suspicious evidence: newline stripping, unquoted splitting/globbing, subshell scope or ignored nested failure changes the result.

Step 5 Common mistakes Narrow the fault
  • Unquoted substitution splitting output.
Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points

Trailing newlines are removed. Unquoted, the result is word-split and globbed — quote it: "$(cmd)". A failing command inside $( ) does not stop the script unless you check $? or use set -e carefully.

Key checks
  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — exit code of the last command
ReferenceWhat it is1 section · depth on demand

Core model

Use $(...) rather than legacy backticks for readable nesting. Remember that the nested command runs in a subshell environment in Bash, its stdout becomes data, trailing newlines are stripped, embedded newlines can participate in splitting if unquoted, and failure status can be obscured by surrounding assignments/commands.

ReferenceImportant terms & boundaries5 sections · depth on demand

What this shows and what it does not

Command-substitution verification shows captured text and nested status handling for tested inputs; it does not preserve arbitrary binary data or parent-shell side effects.

In depth

Command substitution

Command substitution runs a command and inserts its output into the command line. The bash(1) manual page describes the rules:

  • $(command) is the preferred form; backquotes are deprecated.
  • Trailing newlines are removed from the output, but embedded newlines are kept.
  • $(< file) is a faster equivalent of $(cat file).
  • Inside double quotes, the result isn't word-split or glob-expanded.
  • Unquoted, it undergoes both, like any other unquoted expansion.

Forms

FormNotes
$(cmd)Nests easily: $(dirname "$(readlink -f "$0")")
` cmd `Legacy; nesting needs backslashes
"$(cmd)"Keeps spaces, newlines and wildcards as they are
$(< file)Reads a file without starting cat
$( (cd dir && ls) )Space between $( and ( avoids arithmetic confusion

Typical uses

UseExample
Timestamps in file namestar czf "backup-$(date +%F-%H%M).tar.gz" /etc
The directory of a scriptdir="$(cd "$(dirname "$0")" && pwd)"
A countn="$(grep -c ERROR app.log)"
Version checks[[ "$(uname -r)" == 6.* ]]

Exit status

An assignment like out="$(cmd)" takes the exit status of cmd, so if ! out="$(cmd)"; then works. But local out="$(cmd)" and export out="$(cmd)" return the status of local or export, which hides failures. Declare first, then assign.

host$ echo "Kernel $(uname -r) on $(hostname -s)"
Kernel 6.8.0-49-generic on srv1
host$ files="$(ls /etc/ssh/*.pub)"; echo "$files" | wc -l
3
host$ echo $files | wc -l
1
host$ if ! ver="$(app --version 2>&1)"; then echo "app missing: $ver" >&2; fi
host$ f(){ local out; out="$(false)"; echo "status=$?"; }; f
status=1
host$ g(){ local out="$(false)"; echo "status=$?"; }; g
status=0

Reading the example

Quoted, the three file names stay on three lines. Unquoted, word splitting turns them into one line separated by spaces. The two functions show the local pitfall: only the separate assignment keeps the exit status of the command.

Documented example, not captured output.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

How it works at runtime

Command Substitution is part of Shell & Bash → Command Substitution. Command Substitution executes a nested command and substitutes its stdout into the surrounding shell word, removing trailing newlines and then subjecting the result to quoting-dependent argument formation.

Topic-specific state model. Command Substitution executes a nested command and substitutes its stdout into the surrounding shell word, removing trailing newlines and then subjecting the result to quoting-dependent argument formation.

Interpretation rule. - $(cmd) output ≠ exact byte stream because trailing newlines are removed.

  • Unquoted $(cmd) ≠ one argument; word splitting and globbing can follow.
  • Variables changed inside command substitution ≠ parent-shell variables changed.
  • Visible substitution output ≠ nested command success unless status is captured/propagated.

Quick reference

Command substitution inserts a command's output: $(cmd) (preferred, nestable) or backticks.

today=$(date +%F)
kernel="$(uname -r)"
for h in $(cat hosts.txt); do …; done          # splits on whitespace — fragile
while IFS= read -r h; do echo "$h"; done < hosts.txt   # robust line reading
mapfile -t hosts < hosts.txt

Trailing newlines are stripped. Quote the result ("$(cmd)") to keep spaces and avoid glob expansion.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Limits and how it fails

Primary failure point. Command-substitution verification shows captured text and nested status handling for tested inputs; it does not preserve arbitrary binary data or parent-shell side effects.

ReferenceConfiguration & state1 section · depth on demand

Configuration, persistence and lifecycle

Distribution/platform context. Shell Expansion owns combined expansion order; Pipes/Text Processing may produce nested output; this Topic owns capture/substitution semantics.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor doclinux current

Authoritative/upstream documentation reviewed for bounded claims in Shell & Bash → Command Substitution. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
bash command substitution$(command) bashshell backtickscapture command output
Embedded reference data

Quick lookup tables

Command Substitution operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Command Substitution.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateCommand Substitution executes a nested command and substitutes its stdout into the surrounding shell word, removing trailing newlines and then subjecting the result to quoting-dependent argument formation.Establish exactly what this Topic owns before crossing into another subsystem.
Fast verificationPin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test.Use the shortest evidence path first; a fast check is a boundary test, not blanket proof.
Verification chainouter parse → spawn subshell/nested command → nested stdout + status → strip trailing newlines → quote-dependent splitting/globbing → outer argv/value → downstream commandTrace requested/configured state through effective state to the observed workload result.
Failure boundaryCommand-substitution verification proves captured text and nested status handling for tested inputs; it does not preserve arbitrary binary data or parent-shell side effects.Stop broad troubleshooting at the first boundary that is not supported by evidence.
Positive evidenceCorrelated Linux file/text/shell evidence can establish this proof path: outer parse → spawn subshell/nested command → nested stdout + status → strip trailing newlines → quote-dependent splitting/globbing → outer argv/value → downstream commandUse this observation only for the specific claim it actually supports.
Evidence limitIt does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Command-substitution verification proves captured text and nested status handling for tested inputs; it does not preserve arbitrary binary data or parent-shell side effects.Do not promote a local success signal into end-to-end or adjacent-dependency proof.
Next troubleshooting checkContinue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks.Continue to the next unresolved boundary while preserving the original test condition.

Command Substitution · operational reference

Compact Linux state, persistence, verification and boundary reference for fast lookup.

Reference boundaryCommand Substitution
Topic pathShell & Bash → Command Substitution
Runtime stateCommand Substitution executes a nested command and substitutes its stdout into the surrounding shell word, removing trailing newlines and then subjecting the result to quoting-dependent argument formation.
Fast checks- Quote command substitutions when the result is intended as one argument/value. - Test empty output, embedded whitespace/newlines, wildcard characters and failing nested commands. - Capture status separately where nested failure must abort or alter logic. - Avoid using command substitution for binary/NUL-delimited data; verify final argv/value before downstream mutation.
Verification chainouter parse → spawn subshell/nested command → nested stdout + status → strip trailing newlines → quote-dependent splitting/globbing → outer argv/value → downstream command Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary.
Failure boundaryCommand-substitution verification proves captured text and nested status handling for tested inputs; it does not preserve arbitrary binary data or parent-shell side effects. Boundary chain: process/context → userspace configuration → kernel subsystem/resource → device/network/filesystem dependency → effective state → original workload.
Persistence ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?