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[@]}"Report a problem with this exampleOpens a pre-filled issue on GitHub.