Bash Nested Command Substitution
Nested command substitution places one $() inside another $(). The inner command runs first, and its output feeds the outer command.
The inner substitution runs first
The inner echo produces world before the outer echo prints its line. The final line joins both words.
echo "greeting: $(echo "hello $(echo world)")"Quotes inside stay separate from outer quotes
The inner double quotes around the name do not close the outer double quotes. The full name prints with its space intact.
name="Ada Lovelace"
echo "hello: $(echo "$name")"Trailing newlines are stripped
The printf output ends with three newlines, but the capture drops them all. The brackets close right after the word.
text=$(printf 'line\n\n\n')
echo "[$text]"Quoted keeps one word, unquoted splits
The unquoted loop splits the list into three separate words. The quoted loop treats the same list as one single word.
list=$(printf 'red green blue')
echo "unquoted:"
for colour in $list; do
echo "$colour"
done
echo "quoted:"
for colour in "$list"; do
echo "$colour"
doneExample
raw=$(printf 'alpha beta gamma\n\n')
echo "raw: [$raw]"
first=${raw%% *}
echo "first: $first"
echo "nested: $(echo "first is $(echo "$first")")"Key points
- Inner first: the innermost $() runs before the command around it.
- Fresh quotes: quotes inside $() are parsed on their own, so they do not end the outer quotes.
- Trailing newlines: command substitution strips every trailing newline from the captured output.
- Quoted substitution: "$()" keeps the captured text as one word.
- Unquoted substitution: $() without quotes splits the captured text on whitespace.
- Nesting depth: each extra layer runs its inner command first, so read from the inside out.
In this example, the first capture strips the trailing newlines, so the brackets close right after gamma. The cut command takes the first word from the quoted capture. The last line nests one substitution inside another to build the closing message.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does $(printf 'a\n\n') capture?