Overview
Sometimes you want to use the output of one command as part of another. Command substitution captures a command's output and inserts it into your command line or a variable. This lesson explains this powerful shell feature and its pitfalls.
Learning objectives
- Use command substitution to capture output.
- Apply it in variables and command arguments.
- Recognize quoting and security considerations.
Core concept
Command substitution runs a command and replaces it with its output. The modern syntax is $(command) (the older backtick form `command` also works but is less readable and harder to nest). The captured output can be stored in a variable or used as an argument to another command.
today=$(date +%F) # store today's date in a variable
echo "Backup for $today"
How it works
The shell first runs the command inside $( ), captures its standard output (trailing newlines trimmed), and substitutes that text in place before running the outer command. This lets you build dynamic commands — for example, naming a file after the current date, or acting on the results of another command. Prefer $( ) over backticks because it nests cleanly ($(cmd1 $(cmd2))) and is easier to read. Quote the substitution ("$(cmd)") when the output may contain spaces.
Practical example
$ echo "There are $(ls | wc -l) items here"
There are 7 items here
$ backup="archive-$(date +%F).tar"
$ echo "$backup"
archive-2026-09-21.tar
The first embeds a live count into a sentence; the second builds a filename that includes today's date. In both, the inner command runs first and its output is spliced in.
Cybersecurity relevance
Command substitution is heavily used in scripting and automation for security tasks — generating timestamped filenames, feeding one tool's output into another, and building dynamic commands. However, it is also a caution point: substituting untrusted input into a command is dangerous, as it can lead to command injection if that input is attacker-controlled. In scripts that handle external data, you must avoid letting unsanitized values become part of an executed command — a foundational secure-coding lesson expanded in later web-security modules.
Common mistakes
- Using backticks where nested, readable
$( )would be better. - Forgetting to quote
"$(cmd)", causing word-splitting when output contains spaces. - Substituting untrusted input into commands, risking command injection.
Key takeaways
- Command substitution
$(command)runs a command and inserts its output into another command or a variable. - Prefer
$( )over backticks (it nests and reads better); quote"$(cmd)"to handle spaces safely. - It is essential for dynamic scripting, but substituting untrusted input into commands can cause command injection — never build commands from unsanitized external data.
Check your understanding
- What does
$(command)do, and why is it preferred over backticks? - Why is using untrusted input inside command substitution a security risk?

