Ray's Knowledge Base
Unlock

A bash function called with $(...) returns its log lines together with its result

PitfallVerified 30 Sep 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

A script stops with an error that contains a log message instead of a value, for example:

Error: Invalid bump type: Analyzing changes since tag: v2.1.1

The caller is auto_bump=$(analyze_changes), and the function prints status messages with echo before it prints the result (echo "minor").

Cause#

$(...) captures all of the function's stdout. The status lines and the result all go into the variable, so the next check (a case on major, minor or patch) gets the whole block of text.

Fix#

Send every status line in the function to stderr. Only the result stays on stdout:

echo -e "${BLUE}Analyzing changes since tag: ${LAST_TAG}${NC}" >&2
echo "${COMMITS}" >&2
echo "minor"   # the result, on stdout

The status lines still show in the terminal. Do not add | tail -n1 to the caller; it hides the status lines.

Evidence#

Seen in dftracer script/repo/update_version.sh (analyze_changes). After adding >&2 to the 10 log echoes, update_version.sh --dry-run printed Auto-detected minor bump: 4.3.0 with no error.

Also found by searching

  • my shell variable captured from a function contains all the echo log messages, not just the return value
  • how do I return a value from a bash function while still printing progress messages
  • bash command substitution result=$(myfunc) includes debug output, print status to stderr instead
  • bash variable assigned from function output contains my echo log messages, case statement fails
  • how do I print progress messages inside a bash function used with $(func) without polluting the return value?
  • command substitution captures debug echo output in shell script, return value of function mixed with status text