Return Values and Output Capture

Return Values and Output Capture in Bash: --- In a commercial print shop, you send a job to a press and collect the finished sheets from an output tray.


The Analogy: The Print Shop's Job Run and Output Tray

In a commercial print shop, you send a job to a press and collect the finished sheets from an output tray. The press has two chutes. The main chute drops clean, finished sheets into the output tray -- that is standard output, the real product of the run. A second chute drops spoiled sheets and smudge reports into a reject bin off to the side -- that is standard error, the diagnostics and warnings. When you walk up after a run and scoop up the output tray, you are performing command substitution: result=$(command) gathers everything the main chute produced and hands it back as the value you asked for.

There is a tidy habit built into collecting the tray. Presses often spit a few blank sheets at the very end of a run as the rollers clear, and when you square the stack against the table, those trailing blanks fall away -- you keep only the printed sheets. Command substitution does exactly this: it strips every trailing newline from the captured output. A command that prints a line followed by three blank lines hands you back just the line. This is almost always what you want, but it means you cannot use command substitution to capture trailing blank lines that actually mattered, because the squaring-up always discards them.

Each job also runs on its own press in its own bay, sealed for the duration of the run. If an operator reaches inside during the run and nudges a dial -- changing a setting, jotting a note on the press's own scratch pad -- those changes belong to that sealed run and are gone the moment the sheets are handed out and the press resets. This is the subshell nature of command substitution: any variable you assign inside $(...) lives only in the subshell that ran the command, and the surrounding script never sees it. You get the sheets from the tray, but nothing you scribbled on the press comes back with them.

The failure mode is forgetting that the reject bin is separate from the output tray. You send a job, square up a beautiful empty stack from the output tray, and walk away satisfied -- never noticing that the press actually failed and dropped its entire explanation into the reject bin, which you did not collect. In the shell, command substitution captures only standard output; if the command wrote its real answer, or its error message, to standard error, your captured variable is empty or wrong and you proceed on nothing. The disciplined operator always decides, per job, whether to also route the reject chute into the tray (2>&1), send it to the floor (2>/dev/null), or read it separately -- and always checks the press's status light, the exit status, rather than trusting that a full tray means success.


Syntax or Core Structure

Command substitution, written $(command), runs the command and replaces the expression with the command's standard output, minus any trailing newlines. The result is normally assigned to a variable or embedded in another command. Always quote the expansion when using the value, so spaces and newlines are preserved.

#!/usr/bin/env bash
greeting=$(echo "hello there")
echo "captured: [$greeting]"
padded=$(printf 'line\n\n\n')
echo "padded length: ${#padded}"
echo "padded: [$padded]"

Output:

captured: [hello there]
padded length: 4
padded: [line]

The first capture stores the output of echo into greeting, which prints back exactly as produced. The second is the important one: printf 'line\n\n\n' emits the word line followed by three newlines, but command substitution strips all trailing newlines, so padded holds just line -- four characters, as ${#padded} confirms. This trailing-newline stripping is a defining behaviour of command substitution and the reason captured values are clean of the newline a command usually prints at its end. It is what lets name=$(basename "$path") give you a bare name with no newline attached.


Technical Depth: Subshells, Exit Status, and Capturing Many Lines

Ways to capture and what they give you

Several constructs capture output; each has a distinct behaviour worth knowing.

ConstructCapturesNote
the dollar-paren formstdout, trailing newlines strippedruns in a subshell
the dollar-paren-less-file forma file's contents directlyfaster than calling cat
mapfile into an arrayeach line an array elementuse minus t to drop newlines
the 2 to 1 redirectmerges stderr into stdoutso both are captured together

Subshell isolation

Because $(...) runs its command in a subshell, any variable assigned inside it is lost when the substitution finishes. Only the text on standard output crosses back.

#!/usr/bin/env bash
count=0
result=$( count=99; echo "inner count=$count" )
echo "$result"
echo "outer count=$count"

Output:

inner count=99
outer count=0

Inside the substitution, count is set to 99 and echoed, so the captured result contains inner count=99. But that assignment happened in the subshell, so the outer count is still 0 afterward. This is the same subshell isolation that catches people with cmd | while read loops: the work happens in a child shell and its variable changes do not propagate to the parent. If you need a value out, it must travel on standard output and be captured, or be written through a nameref in the current shell.

Capturing the exit status too

Unlike a local var=$(cmd) declaration, a plain var=$(cmd) assignment does let the command's exit status through to $? -- but you must read $? on the very next line, before any other command overwrites it.

#!/usr/bin/env bash
probe() { echo "some output"; return 4; }
out=$(probe)
rc=$?
echo "out=[$out]"
echo "rc=$rc"

Output:

out=[some output]
rc=4

The assignment out=$(probe) captures some output and, because it is a plain assignment rather than a local declaration, $? afterward is probe's status of 4. The critical discipline is capturing rc=$? immediately: the very next command sets its own status, so echo "out=[$out]" would overwrite $? if you tried to read it later. Capture the output and the status on consecutive lines, then use them freely.

Many lines into an array, and the stderr question

To capture multi-line output as separate elements, mapfile -t reads each line into an array. And remember that $(...) captures only standard output; standard error goes elsewhere unless you redirect it.

#!/usr/bin/env bash
lines=$(printf 'a\nb\nc\n')
echo "as string, newlines intact: [$lines]"
mapfile -t arr < <(printf 'a\nb\nc\n')
echo "array count: ${#arr[@]}"
echo "arr[1]=${arr[1]}"
emit() { echo "to-stdout"; echo "to-stderr" >&2; }
captured=$(emit 2>/dev/null)
echo "captured=[$captured]"

Output:

as string, newlines intact: [a
b
c]
array count: 3
arr[1]=b
captured=[to-stdout]

Capturing into a single string keeps the internal newlines (only the trailing one is stripped), so lines prints across three lines inside the brackets. Using mapfile -t arr with a process substitution splits the same output into a three-element array, where arr[1] is the second element, b. The last block proves the stderr point: emit writes to both streams, but captured=$(emit 2>/dev/null) throws standard error away and keeps only to-stdout. Had emit written its real answer to standard error, captured would be empty -- exactly the reject-bin trap from the analogy.


Real World Example: A Log-Level Counter

A common task is to summarise counts from a stream: read log lines, tally how many of each level, and print a sorted report. This program captures a pipeline's output into an array with mapfile, then parses each captured row. It uses fixed input so the counts are reproducible.

#!/usr/bin/env bash
set -u
LC_ALL=C

logdata() {
  cat <<'LOG'
INFO start
WARN low disk
INFO tick
ERROR crash
WARN low disk
INFO tick
LOG
}

mapfile -t counts < <(logdata | awk '{print $1}' | sort | uniq -c | sort -rn)

echo "distinct levels: ${#counts[@]}"
total=0
for row in "${counts[@]}"; do
  read -r n lvl <<< "$row"
  total=$(( total + n ))
  printf '%-6s %d\n' "$lvl" "$n"
done
echo "total lines: $total"

Output:

distinct levels: 3
INFO   3
WARN   2
ERROR  1
total lines: 6

Trace the pipeline that feeds the capture. logdata emits six lines; awk '{print $1}' keeps just the level word; sort groups identical words together; uniq -c prepends each group's count; and sort -rn orders the groups by count, highest first. The result -- three rows reading 3 INFO, 2 WARN, 1 ERROR with leading spaces from uniq -- is captured line by line into the counts array by mapfile -t. The loop then uses read -r n lvl to split each row, which conveniently ignores the leading whitespace, and tallies a grand total of six lines. The report is aligned with printf field widths.

The program hides three real defects. First and most dangerous, a failure anywhere in the captured pipeline is invisible: mapfile reports only its own success, and without set -o pipefail a broken awk or a missing command would leave counts empty and print distinct levels: 0 with no error at all, so the report would silently under-count. Second, the ordering relies on the counts being distinct: sort -rn gives no guaranteed order among equal counts unless -s for stable sort is added, so two levels tied at the same count could swap places between runs on some systems. Third, the read -r n lvl parse assumes each level is a single word; a level label containing a space would spill into lvl incorrectly, and a malformed uniq row would misparse -- the capture is only as trustworthy as the format it assumes.


Common Mistakes

  1. Forgetting that command substitution strips trailing newlines. $(cmd) removes every trailing newline, so you cannot use it to capture output whose trailing blank lines are significant. When they matter, capture with mapfile or read the raw bytes another way.
  1. Expecting variable assignments inside $() to persist. Command substitution runs in a subshell, so a variable set inside $(...) is gone afterward. Only standard output crosses back; to export state, echo it and capture, or use a nameref in the current shell.
  1. Reading $? too late after a capture. out=$(cmd) sets $? to the command's status, but the next command overwrites it. Capture rc=$? on the immediately following line, before any other command runs, or the status is lost.
  1. Assuming a capture includes stderr. $(cmd) captures only standard output. If a command writes its answer or its error to standard error, the captured variable is empty or wrong. Redirect deliberately with 2>&1 to merge, or 2>/dev/null to discard.
  1. Leaving a capture unquoted. for x in $(cmd) word-splits and glob-expands the output, mangling values with spaces or special characters. Quote the expansion -- "$(cmd)" -- or capture line by line with mapfile when the output has structure.
  1. Not setting pipefail when capturing a pipeline. A pipeline's exit status is that of its last stage by default, so an earlier stage failing is masked. Enable set -o pipefail when the success of every stage matters to the captured result.
  1. Using backticks instead of $(). Old-style backtick substitution does not nest cleanly and has awkward quoting rules. Prefer $(...), which nests, quotes predictably, and reads far better in anything but the most trivial case.
  1. Capturing huge output into a variable. A command producing megabytes of output stored in one variable wastes memory and is slow to process. Stream it through a pipe or read it incrementally instead of capturing the whole thing at once.
  1. Splitting multi-line output by hand. Parsing $(cmd) with fragile string operations to get individual lines is error-prone. mapfile -t arr < <(cmd) reads each line into an array element cleanly and handles the trailing newline for you.

Best Practices

  • Quote every command substitution you use as a value. Write "$(cmd)" so spaces, tabs, and newlines in the output are preserved. Leave it unquoted only in the rare, deliberate case where you want the shell to split the result into words.
  • Capture output and exit status on consecutive lines. When you need both, write out=$(cmd) then rc=$? immediately, before anything else runs. This is the only reliable way to keep the status that goes with the captured output.
  • Decide explicitly what happens to stderr. For each capture, choose to merge stderr with 2>&1, discard it with 2>/dev/null, or leave it on the terminal. Never assume a capture is complete without knowing which stream the command uses for its real output.
  • Use mapfile for multi-line captures. When output is a list of lines, mapfile -t arr < <(cmd) gives a clean array with newlines stripped, which is far more robust than splitting a single captured string by hand.
  • Enable pipefail when a captured pipeline's stages all matter. set -o pipefail makes the pipeline fail if any stage fails, so a broken early stage does not silently yield empty or partial captured data.
  • Prefer $(<file) for reading a file's contents. To capture a file into a variable, $(<file) is faster and clearer than $(cat file) because it avoids launching a separate process.
  • Keep captured data small and structured. Capture summaries, counts, and single values rather than enormous raw dumps. For large streams, process line by line through a pipe instead of loading everything into memory.
  • Always use $() rather than backticks. The modern form nests, quotes cleanly, and is unambiguous. Reserve backticks only for reading legacy scripts, never for new code.

Practice Exercises

  1. Trailing-newline proof. Capture the output of a command that prints a word followed by several blank lines, and print the length of the captured value. Show that the trailing blanks are gone, then capture the same output with mapfile and show how many elements result, explaining the difference.
  1. Status with output. Write a function that prints a value and returns a non-zero status. Capture both its output and its exit status correctly, then deliberately read $? one line too late and show how the status is lost. Explain the fix in a comment.
  1. Stderr routing. Write a command that prints a result to stdout and a warning to stderr. Capture it three ways -- default, with 2>&1, and with 2>/dev/null -- and show how the captured value differs in each case. State which routing you would choose for a value you must parse.
  1. Robust pipeline capture. Capture a multi-stage pipeline into an array with mapfile, first without pipefail and then with it, and introduce a failing stage. Show that only the pipefail version lets you detect the failure, and explain why the array is empty in both cases.