Expansion and Data
Command Substitution
Capturing Output
Command substitution runs a command and stores its stdout in a variable. It is a common way to build names, paths, and small reports.
Program
Play the script to watch printf produce text that becomes the value of stamp.
command_substitution.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
today="2026-05-28"
stamp="$(printf 'run-%s' "$today")"
echo "$stamp"
today ← 2026-05-28
3today="2026-05-28"4stamp="$(printf 'run-%s' "$today")"values this step2026-05-28todaystamp ← run-2026-05-28
3today="2026-05-28"4stamp="$(printf 'run-%s' "$today")"5echo "$stamp"values this steprun-2026-05-28stamp2026-05-28todayecho "$stamp"
4stamp="$(printf 'run-%s' "$today")"5echo "$stamp"outputrun-2026-05-28values this steprun-2026-05-28stamp
Follow the Capture
todaystarts as2026-05-28.printf 'run-%s' "$today"buildsrun-2026-05-28.$(...)captures that text without printing it right away.stampstoresrun-2026-05-28.echo "$stamp"printsrun-2026-05-28. | step | value | | --- | --- | |today|2026-05-28| | captured stdout |run-2026-05-28| |stamp|run-2026-05-28| | printed output |run-2026-05-28|
command substitution
`$(...)` runs the command inside and replaces it with stdout.
printf
`printf` formats text predictably and is often safer than `echo` for generated data.
Exercise: command_substitution.sh
Reproduce run-2026-05-28, then change today to a new date and predict the new stamp before running it.