0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Return Value from Function in Bash Script

In Bash, functions cannot return values like other languages; instead, use echo inside the function to output the value and capture it with command substitution like result=$(my_function). Alternatively, use global variables or the return statement for exit codes (0-255).
📐

Syntax

In Bash, functions return values by printing output with echo. You capture this output outside the function using command substitution. The return statement is used only for exit status codes (0-255), not for returning data.

  • function_name() { commands; echo value; } - prints the value
  • result=$(function_name) - captures printed value
  • return n - sets exit status (integer 0-255)
bash
my_function() {
  echo "Hello"
  return 0
}

result=$(my_function)
echo "$result"
Output
Hello
💻

Example

This example shows a function that calculates the sum of two numbers and returns the result by printing it. The caller captures the output using command substitution.

bash
sum() {
  local a=$1
  local b=$2
  echo $((a + b))
}

result=$(sum 5 7)
echo "Sum is: $result"
Output
Sum is: 12
⚠️

Common Pitfalls

Many beginners try to use return to send back values like in other languages, but in Bash it only sets the exit status (0-255). Trying to return strings or large numbers with return will cause errors or unexpected results.

Always use echo to output values and capture them with command substitution. Also, avoid using global variables unless necessary, as they can cause side effects.

bash
wrong_return() {
  return "Hello"
}

# This will cause an error or unexpected behavior

correct_return() {
  echo "Hello"
}

result=$(correct_return)
echo "$result"
Output
Hello
📊

Quick Reference

ConceptUsageNotes
Return valueUse echo inside functionOutputs value to capture
Capture outputUse result=$(function_name)Stores function output in variable
Exit statusUse return n with 0-255Indicates success or error code
AvoidUsing return for strings or large numbersCauses errors or truncation

Key Takeaways

Use echo inside Bash functions to output values you want to return.
Capture function output with command substitution: result=$(function_name).
The return statement only sets exit status codes (0-255), not data values.
Avoid using return for strings or large numbers; it causes errors.
Prefer local variables and echo for clean, side-effect-free functions.