Use this when capturing command output into variables.
Command Substitution
Command substitution runs a command and inserts its output, written $(command), such as today=$(date +%F). Prefer it over backticks and quote it to keep spaces intact.
1. $(cmd) captures output.
2. Quote the result.
3. Nested $( ) is readable.
4. Trailing newlines stripped.
5. Check exit status separately when needed.
command → stdout captured → variable
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Common mistakes Narrow the fault
- Old backticks that are hard to nest.
- Ignoring that a failed substitution still returns empty text.
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.
- Use $(command), not backticks.
- Quote the result.
- Trailing newlines are removed.
now="$(date -u +%FT%TZ)"— command substitution- $( ) instead of backticks — readability
- Check command success — set -e doesn't catch in assignments always
ReferenceWhy it matters1 section · depth on demand
What it is
Command substitution $(command) inserts a command's output into another command or variable.
ReferenceHow it works1 section · depth on demand
Example
backup_file="backup-$(hostname)-$(date +%F).tar.gz"
count=$(grep -c ERROR /var/log/app.log || true)
Quote the result ("$(...)") so spaces and newlines in the output are kept.
ReferenceImportant terms & boundaries2 sections · depth on demand
How it works
The shell runs the command in a subshell, captures its stdout, strips trailing newlines and substitutes the text. Exit status of the substitution is available in $? right after an assignment (x=$(cmd); echo $?), which lets scripts detect failures.
Example
now=$(date +%F)
ver=$(ssh "$host" 'cat /etc/os-release' | grep ^VERSION_ID)
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Bash Automation > 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%