Command Substitution Patterns
Uses command substitution to capture command output, nest substitutions, and combine with variable assignment for dynamic script behavior.
Code
#!/usr/bin/env bash
set -euo pipefail
# Basic command substitution
current_date=$(date +%Y-%m-%d)
echo "Date: $current_date"
# Preferred $() syntax over backticks
files_count=$(ls -1 /etc 2>/dev/null | wc -l)
echo "Files in /etc: $files_count"
# Nested command substitution
grandparent=$(dirname "$(dirname "$(pwd)")")
echo "Grandparent dir: $grandparent"
# Substitution in strings
host=$(hostname)
user=$(whoami)
echo "${user}@${host}:$(pwd)"
# Substitution with arithmetic
size=$(stat -c%s /etc/hostname 2>/dev/null || echo 0)
echo "Hostname file size: $size bytes"
echo "KB: $(( size / 1024 )) KB"
# Substitution in conditionals
if [[ $(id -u) -eq 0 ]]; then
echo "Running as root"
else
echo "Running as $(whoami)"
fi
# Capture exit status separately
output=$(grep "localhost" /etc/hosts 2>/dev/null) || true
status=$?
if (( status == 0 )); then
echo "Found: $output"
elif (( status == 1 )); then
echo "Not found"
fi
# Array from command output
mapfile -t conf_files < <(find /etc -maxdepth 1 -name "*.conf" 2>/dev/null)
echo "Config files found: ${#conf_files[@]}"How it works
set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.
The work is delegated to mapfile, chained through 5 pipes so each stage’s output feeds the next.
Points of care
- The pipeline is 5 stages deep — when it misbehaves, split the pipe and test the stages separately.
The key statements that remain
current_date=$(date +%Y-%m-%d)
files_count=$(ls -1 /etc 2>/dev/null | wc -l)
grandparent=$(dirname "$(dirname "$(pwd)")")
Interactive Tools for This Topic
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `mapfile` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.