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"
  1. today ← 2026-05-28

    3today="2026-05-28"4stamp="$(printf 'run-%s' "$today")"
    values this step2026-05-28today
  2. stamp ← run-2026-05-28

    3today="2026-05-28"4stamp="$(printf 'run-%s' "$today")"5echo "$stamp"
    values this steprun-2026-05-28stamp2026-05-28today
  3. echo "$stamp"

    4stamp="$(printf 'run-%s' "$today")"5echo "$stamp"
    outputrun-2026-05-28
    values this steprun-2026-05-28stamp

Follow the Capture

  1. today starts as 2026-05-28.
  2. printf 'run-%s' "$today" builds run-2026-05-28.
  3. $(...) captures that text without printing it right away.
  4. stamp stores run-2026-05-28.
  5. echo "$stamp" prints run-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.