Skip to the workspace
Pebellslearn by building
Input and Output  ›  Lesson

Command Substitution: Capture Output

Command substitution 12 minCommand substitution, written $(command), runs a command and replaces itself with the command's output, minus trailing newlines.

shell bash / Command Substitution: Capture Output

Explore each scene at your own pace.

01 · The rule

The rule

Command Substitution: Capture Output

Command substitution, written $(command), runs a command and replaces itself with the command's output, minus trailing newlines.

Capture command output while accounting for stripped trailing newlines.

The very first version of backup.sh had the date typed into the archive name, and the "same way again?" test flagged it. The fix is to let the date command supply it. To do that, a script needs to take what a command prints and use it as a value.

The rule

$( ) runs a command and pastes its output in its place.

stamp="$(date +%F)"                          # 2026-09-25
archive="$dest/${name}-${stamp}.tar.gz"
echo "Today is $(date +%A)"                  # Today is Friday
count="$(find "$src" -type f | wc -l)"       # how many files

What happens, in order:

  1. Bash runs the command inside $( ) in a subshell, a temporary copy of itself.
  2. It collects everything the command prints on standard output.
  3. It removes trailing newlines, then puts the text where $( ) stood.

Three consequences:

  • Quote it like a variable: "$(...)". The result is split on spaces if left bare.
  • Anything the inner command changes about its shell, such as cd or a variable, vanishes when the subshell ends.
  • Error messages are not captured; they go to the terminal. Only standard output is pasted in.

You will also meet the old backquote form, `date +%F`. It does the same job, but it is harder to read and to nest. Prefer $( ), which nests cleanly: $(basename "$(pwd)").

A cousin, process substitution, looks similar but hands over a file name instead of text, so a command that expects files can read another command's output: diff <(ls dir1) <(ls dir2).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.