Command Substitution with $(...)
Command substitution lets one command use the output of another. Bash runs the command written inside $(...), captures what it prints, and replaces the whole $(...) expression with that text. It is how a script stores the current date in a variable, counts the files in a folder, or builds a command from the result of an earlier one.
Understanding the Concept
Normally a command prints its output to the terminal. With command substitution, Bash intercepts that output instead and puts it into the command line, as if you had typed it yourself.
today=$(echo 2026-11-21)
echo "Today: $today"
Output:
Today: 2026-11-21
Bash ran echo 2026-11-21, captured the text 2026-11-21 that it would have printed, and assigned that text to the variable today. The second line then used the variable. In real scripts the inner command is usually something like date, but echo keeps the example predictable.
Command substitution is an expansion, so Bash performs it while processing the line, before the outer command runs. The outer command never sees $(...). It only sees the text that replaced it.
Syntax
$(command)
The command may be a single program, a pipeline, or several commands separated by semicolons. Everything written between the parentheses runs in a subshell, which is a child copy of the current shell.
count=$(ls d | wc -l)
echo "d has $count entries"
With a folder d that contains three files, the output is:
d has 3 entries
The pipeline ls d | wc -l ran inside the substitution. ls listed the files, wc -l counted the lines, and the number 3 replaced the $(...) expression.
You can also place a substitution directly inside a double-quoted string:
printf 'hello file\nline2\n' > data.txt
echo "Lines in data.txt: $(wc -l < data.txt)"
Output:
Lines in data.txt: 2
wc -l < data.txt reads the file through input redirection, so wc prints only the number without the file name.
The Older Backtick Form
An older syntax wraps the command in backticks:
echo `echo old-style`
echo $(echo new-style)
Output:
old-style
new-style
Both forms do the same job, but $(...) is easier to read and much easier to nest. Inside backticks, an inner pair of backticks must be escaped with backslashes. Inside $(...), nesting needs no escaping:
echo "nested: $(echo "outer $(echo inner)")"
echo `echo \`echo inner\``
Output:
nested: outer inner
inner
In the first command, each pair of quotes inside a $(...) is independent of the quotes outside it, so you can nest without any extra escaping. The backtick version needs