LOGBOOK

HELP

Quiz Entry - updated: 2026.07.05

What is command substitution and how do you use it?

Command substitution $(command) runs a command and replaces itself with that command's output — so you can capture a result into a variable or drop it inline.

Bash runs whatever is inside $(...), grabs its stdout, strips the trailing newline, and substitutes the text in place. That lets a script use computed values — today's date, the current user, the output of apropos — instead of hard-coded ones.

**Prefer $(...)` over the old backtick form `` `command` ``.** Two concrete reasons: `$() nests cleanly$(dirname $(which python))` works, whereas nested backticks require ugly escaping — and `$() is far easier to read because $ and ( stand out, while backticks are easy to confuse with single quotes.

# Store command output
today=$(date +%Y-%m-%d)
user=$(whoami)
files=$(ls *.txt)

# Use directly
echo "Today is $(date)"
echo "You are logged in as $(whoami)"

Example script:

#!/bin/bash
keyword="player"
results=$(apropos $keyword)
echo "Man pages for '$keyword':"
echo "$results"

Nested substitution:

# Modern syntax supports nesting
dir=$(dirname $(which python))

Tip: Prefer $(command) over backticks - it's clearer and nests properly.

Go deeper:

From Quiz: LIOS / Bash Scripting and Automation | Updated: Jul 05, 2026