$_ CLI In Depth
Learning progress 0%
lesson expansion quoting word-splitting

Command Substitution

5 min read Module 8: Expansion, Quoting & Word Splitting Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:17

Capturing output into a value

The form $(command) runs command in a subshell, collects everything it writes to standard output, and places that text where the substitution appeared. Standard error is not captured. It still goes to your terminal, so warnings remain visible while the value is being built. The older backtick form, written with a pair of backtick characters around the command, does the same job. Prefer the $(...) form. It nests cleanly, and it does not need escaping when the inner command has its own quotes.

BASH3 lines
here=$(pwd)
echo "You are in $here"
echo "Parent is $(basename "$(dirname "$here")")"
TEXT2 lines
You are in /workspace
Parent is /

The second line nests one substitution inside another. Bash evaluates the innermost command first, then the outer one, which is the natural reading order. Notice that the inner double quotes protect the path from splitting while the outer substitution runs.

Multi-line output

Newlines in the middle of a result are kept. Only the trailing ones are removed. That makes multi-line output usable, but only if the substitution is quoted. An unquoted substitution is split at spaces, tabs, and newlines alike, so the line structure disappears. The example below stores two lines and then prints the value twice. The first echo loses the line break because splitting turned the newline into a space. The second keeps it because the quotes preserved the value as one word.

BASH3 lines
x=$(printf 'a\nb\n')
echo $x
echo "$x"
TEXT3 lines
a b
a
b

When you need to process each line, a substitution is the wrong tool. Redirect the command into a loop with while read, or read the lines into an array. The substitution is best for a single value, and it is most reliable when every use of it is quoted.

Trailing newlines are removed

Bash removes every trailing newline from the captured text. Internal newlines are kept, but the ones at the end disappear, so a value that ends in a line break is not preserved exactly. This is convenient for values such as a single word, and it is a trap for files whose exact final newline matters. The command below prints the value inside brackets, which makes the removal visible.

BASH2 lines
name=$(printf 'Ada\n\n')
printf '[%s]\n' "$name"
TEXT1 lines
[Ada]

If you need the exact bytes of a command's output, redirect that output to a file instead of capturing it in a variable. The file keeps every byte, and you can read it back with a tool that does not strip anything.

Quoting controls splitting

An unquoted substitution behaves like an unquoted parameter. Its result is split into words at the characters in IFS, and each word is then subject to filename expansion. A quoted substitution stays one word. The rule is the same one you saw in the expansion order lesson, applied to output from a command rather than a variable.

For a file name stored in a variable, always quote the substitution when you use it as an argument. Otherwise a name with spaces will become several arguments, and a name that contains a star may match other files. Quoting is inexpensive and prevents an entire category of bugs.

Substitutions run in a subshell

Each substitution runs in a child copy of the shell. Anything the command changes in that copy is lost when it finishes. This matters when you try to set a variable inside the substitution. The next example shows that the outer variable is unchanged.

BASH4 lines
v=1
out=$(v=2; echo "inner sees $v")
echo "$out"
echo "outer sees $v"
TEXT2 lines
inner sees 2
outer sees 1

Working with the status of a substitution is also different from working with a plain command. In an assignment such as x=$(false), the exit status of the assignment is the exit status of the substitution, so echo $? prints 1. A common mistake is export x=$(false). The export builtin succeeds, so the failure is hidden. Declare the variable first, then assign it on a separate line when the status matters.

A bash shortcut for reading files

Bash has a special form, $(< file), that reads a file into a substitution without running cat. It is faster, and it is useful in scripts that read one file repeatedly. The form is a bash feature, so a script that must run under a strict POSIX shell should use $(cat file) instead. Like the other substitutions, it still removes trailing newlines.

Substitutions in tests and loops

Command substitutions are most useful inside tests and loops, where they replace a temporary file. The test [ "$(wc -l < notes.txt)" -gt 2 ] is true when the file has more than two lines, and it never creates a file on disk. Always quote the substitution inside a test, because an empty result would otherwise remove an argument and produce a confusing syntax error. Inside a loop, a substitution can feed a list of values to the loop header. Remember that the loop header is subject to word splitting, so names with spaces need a different approach, which the filename lesson covers.

BASH4 lines
count=$(wc -l < notes.txt)
if [ "$count" -gt 2 ]; then
  echo "more than two lines"
fi
TEXT1 lines
more than two lines

Choosing between capture and redirection

Capture a value when the result is short and you will use it several times in a script, such as a count, a path, or a version string. Redirect to a file when the output is large, binary, or needs to be exact. A pipeline is often clearer than either: wc -l < notes.txt produces only the number, and that number is easy to store. The rest of this module returns to substitutions when it discusses arithmetic and word splitting, which both depend on the value the substitution produces.

The order of shell expansions

Visualizer

Bash rewrites each word in a fixed sequence: braces, tilde, parameters and substitutions, word splitting, pathnames, then quote removal.

1 / 6
the line as typed
echoword 0
~/"$name"word 1
$(date +%Y)word 2
*.txtword 3

Bash parses the line into four words. Nothing is expanded yet, so each word is still its literal text.

name="my docs"; printf "[%s]\n" ~/"$name" $(date +%Y) *.txt
Terminal lab · 3 steps · real Linux in your browser

Capture and use command output

Strip trailing newlines, count lines into a value, and read a file with the bash shortcut form.

01
See trailing newlines disappear
Bash keeps the text of the output but removes the trailing newlines when it captures the value. Run this in /workspace. ``bash name=$(printf 'Ada\n\n'); printf '[%s]\n' "$name" > trimmed.txt `` Run cat trimmed.txt. The brackets should surround Ada with no blank lines between them.
Show hint for step 1
Capture printf output with two newlines into a variable, then print the variable inside brackets. Redirect the result to trimmed.txt.
02
Capture a count from a command
The file notes.txt has three lines. When wc reads from standard input, it prints only the number, which makes it safe to capture. ``bash lines=$(wc -l < notes.txt) echo "$lines" > count.txt `` The file count.txt should contain 3.
Show hint for step 2
Use wc -l with input redirected from notes.txt, so the output has no file name. Store it in lines and write it to count.txt.
03
Read a file with the $(&lt; file) shortcut
The shortcut $(&lt; message.txt) reads the file into the substitution. The file contains the phrase hello with two spaces between the words, so the quotes are needed to keep them. ``bash msg=$(< message.txt) printf '%s\n' "$msg" > copy.txt `` The file copy.txt should contain hello, two spaces, and world.
Show hint for step 3
Keep the two spaces by quoting the variable in the printf. Write the result to copy.txt.
Check yourself Question 1 of 4
Concept Check Where standard error goes recall

In x=$(ls /nope), what does bash do with the error message that ls prints to standard error?

Recap & Key Takeaways

The substitution $(command) replaces itself with the standard output of the command, but standard error still goes to the terminal.
Trailing newlines are removed from the captured text, so the value is not always byte-for-byte identical to the output.
An unquoted substitution is word split and globbed like an unquoted parameter, so quote it when you need one argument.
Substitutions run in a subshell, so variables set inside them do not change the outer shell.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue