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.
here=$(pwd)
echo "You are in $here"
echo "Parent is $(basename "$(dirname "$here")")"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.
x=$(printf 'a\nb\n')
echo $x
echo "$x"a b
a
bWhen 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.
name=$(printf 'Ada\n\n')
printf '[%s]\n' "$name"[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.
v=1
out=$(v=2; echo "inner sees $v")
echo "$out"
echo "outer sees $v"inner sees 2
outer sees 1Working 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.
count=$(wc -l < notes.txt)
if [ "$count" -gt 2 ]; then
echo "more than two lines"
fimore than two linesChoosing 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.