0
0
Bash Scriptingscripting~5 mins

Return values (return and echo) in Bash Scripting

Choose your learning style9 modes available
Introduction
In bash scripts, you use return and echo to send back results from functions. This helps you reuse code and get information from functions.
When you want a function to tell if it succeeded or failed using return codes.
When you want a function to send back some text or data using echo.
When you need to capture the output of a function to use later in your script.
When you want to check the status of a command inside a function.
When you want to print messages from a function to the screen.
Syntax
Bash Scripting
function_name() {
  # Use return to send a number (0-255) as status
  return <number>

  # Use echo to print text output
  echo "some text"
}
The return command only sends back a number between 0 and 255, usually 0 means success and other numbers mean errors.
Echo prints text to the screen or to wherever the output is directed. You can capture this output in a variable.
Examples
This function returns 0 if the number is even, 1 if odd.
Bash Scripting
check_even() {
  if (( $1 % 2 == 0 )); then
    return 0
  else
    return 1
  fi
}
This function prints a greeting message using echo.
Bash Scripting
greet() {
  echo "Hello, $1!"
}
Captures the output of greet function into a variable and prints it.
Bash Scripting
result=$(greet Alice)
echo "$result"
Sample Program
This script defines two functions: one returns a status code to say if a number is even, the other prints a greeting. It then uses them and shows the results.
Bash Scripting
#!/bin/bash

is_even() {
  if (( $1 % 2 == 0 )); then
    return 0
  else
    return 1
  fi
}

say_hello() {
  echo "Hello, $1!"
}

number=4
say_hello "User"

if is_even $number; then
  echo "$number is even."
else
  echo "$number is odd."
fi
OutputSuccess
Important Notes
Return values in bash functions are limited to numbers 0-255 and usually indicate success (0) or failure (non-zero).
Use echo to send text output from functions, which you can capture with command substitution $(...).
Do not confuse return and echo: return is for status codes, echo is for output data.
Summary
Use return to send back a number status from a function.
Use echo to print text output from a function.
Capture echo output with $(...) to use it in your script.