Command substitution
How it works
Command substitution, $(command), runs a command in a subshell environment and substitutes its standard output, removing all trailing newline characters. Internal newlines remain. Standard error is not captured unless explicitly redirected, a topic covered later. Prefer $(...) to legacy backticks because nesting is clearer. A plain assignment such as result=$(...) preserves spaces; quote the variable when passing it to a command. An assignment-only command with substitution has the exit status of the last substitution. This is not a way to store arbitrary binary data; Bash variables cannot preserve NUL bytes.
Run each example separately in a noninteractive Bash 5.2 script in a fresh empty practice directory, with default options and C locale. Output is shown separately; do not enter it as code.
Capture a report label
label=$(printf '%s\n' 'Daily report')printf '[%s]\n' "$label"Expected stdout:
[Daily report]The newline is removed; the space is preserved.
Internal and trailing newlines
text=$(printf 'one\ntwo\n\n')printf '[%s]\n' "$text"Expected stdout:
[onetwo]Only the trailing newlines are removed.
Status and child state
mode=parentresult=$(mode=child; printf '%s' "$mode"; false)status=$?printf '%s\n' "$result" "$mode" "$status"Expected stdout:
childparent1The child prints a value but fails; its assignment does not update the parent.
Common mistakes
Capturing output does not guarantee success. Save or check the assignment status before running another command. Do not expect trailing newlines to survive or changes in the child shell to update the parent.
Practice
Capture alpha and beta on separate lines, with two trailing newlines. Print the captured value in brackets and predict where the closing bracket appears.
Next: Arithmetic expansion basics