Web Analytics

Return Values

Intermediate~20 min read

Bash functions signal success or failure using the exit status (0 = success, non-zero = failure). To get computed data, print it and capture via command substitution.

Exit Status (Success/Failure)

Any command or function leaves a status code in $?. In conditions, a status of 0 is treated as true.

Returning Data

Use echo inside the function and capture the output with var=$(func args).

Output
Click Run to execute your code
Pro Tip: For complex outputs, print in a stable, parseable format (e.g., TSV or JSON) so callers can reliably consume results.
Caution: Don’t mix diagnostic output with data output. Send logs to stderr using echo "msg" 1>&2 if needed.

Common Mistakes

1) Using return for arbitrary data

# Wrong
sum() { return $(( $1 + $2 )); }

# Correct
sum() { echo $(( $1 + $2 )); }

2) Ignoring function exit status

# Wrong
maybe_fail() { false; echo 42; }
result=$(maybe_fail)
echo "$result"  # Misleading if command failed

# Correct
if result=$(maybe_fail); then
  echo "$result"
else
  echo "error" 1>&2
fi

Exercise: Max of Two

Task: Implement max that echoes the larger of two integers. Return non-zero if arguments are invalid.

  • Accept exactly two arguments.
  • Handle negative numbers correctly.
Output
Click Run to execute your code
Show Solution
max() {
  [[ $# -eq 2 && $1 =~ ^-?[0-9]+$ && $2 =~ ^-?[0-9]+$ ]] || return 1
  (( $1 >= $2 )) && echo "$1" || echo "$2"
}

max 5 9

Summary

  • Use exit status for control flow (0 = success).
  • Use echo and $(...) to return data.
  • Check $? or use if func; then ... patterns.

What's Next?

Next, manage variable visibility and side effects in Function Scope.