Return Values From Bash Function

Return values are an integral part of a Bash function. The bash function returns values by using the return statement. There are some other techniques as well like using echo command or global variables. In this article, I will show 6 examples of how the bash function returns values such as integer, string, boolean, and array. Additionally, the importance of return values used in error handling will be addressed. I will also cover some pitfalls in returning values and their solutions for more robust bash scripting.

What is a Function in Bash?

Bash function is a set of commands grouped under a single name that is reusable and performs a specific task. To make a script more readable and organized, using the bash function is a good idea. It helps to avoid writing the same code or commands repeatedly. You can just call the function anywhere in the script to accomplish the desired task. The bash function uses return values to indicate the success or failure of the last executed command.

The syntax of a bash function is as follows:

function_name() {
  # Commands or code blocks
}
EXPLANATION

function_name: This is the name you give to your function. It follows the same rules as variable names in Bash. Also, you can use the function keyword before the function name to create a function.

(): These parentheses indicate the start and end of the function parameter list. You can omit the parentheses if your function doesn’t take any parameters.

# Commands or code blocks: This is the function body where the commands or code blocks are placed to execute the function.

{}: These curly braces contain the body of the function.

What are Return Values in Bash Function?

Returns values are the values that a bash function returns through the exit status when the function is completed. The exit status captures the return value of the bash function which is stored in a special variable $?. A return statement can be used to return an integer value between 0 and 255. Here, 0 indicates success and a non-zero value indicates failure of the last executed command. To return other values like string or array, using echo command or global variables is a great way.

6 Examples of Return Values From Bash Function

In this section, how the bash function returns one value or multiple is discussed. Additionally, the bash function can return values as strings or arrays using echo command or global variables. Most importantly, these return values can be used in handling errors. Let’s delve into the details.

1. Return One Value as Integer

To return one integer value between 0 to 255 from the bash function, use the return statement. This statement ends the function by returning the exit status to the caller function. The exit status is the return value of the bash function. Follow the script to see how it works:

#!/bin/bash
# Function to multiply two numbers and return the result as an integer
  multiply_numbers() {
  local num1=$1
  local num2=$2
  local multiplication=$((num1 * num2))
  # Returning the multiplication as the exit status
  return $multiplication
}
# Call the function and capture the return value
multiply_numbers 5 3
result=$?
echo "Multiplication result: $result"
EXPLANATION

First, a Bash function is defined named multiply_numbers that takes two parameters (num1 and num2), calculates their product (multiplication), and returns the result as the exit status. The local keyword is used to make the variable local to the function. multiply_numbers 5 3 calls the function with arguments 5 and 3, and the exit status of the function is captured in the variable “result” using $?. echo "Multiplication result: $result" prints the multiplication result obtained from the exit status of the function.

returning values as integer in bash

As you can see, the bash function returns 15 and prints it in the terminal. However, this script cannot return a value more than 255. To avoid this issue, follow the Exceeding Return Value Limit section.

2. Return Multiple Values

Multiple values can be returned from the bash function using a Bash array. For that, define a function and then create an array that includes the values that will be returned from the function using the echo command. Here’s how:

#!/bin/bash
# Define a function that returns multiple values using an array
function multiple_values() {
  # Create an array and assign values to it
  local array=("Ubuntu" "Linux" "Red-hat")
  # Return the array
  echo "${array[@]}"
}
# Call the function and store the result in an array
result=($(multiple_values))
# Access the individual values from the array
echo "First value: ${result[0]}"
echo "Second value: ${result[1]}"
echo "Third value: ${result[2]}"
EXPLANATION

The script defines a function multiple_values that creates an array with three values (“Ubuntu”, “Linux”, and “Red-hat”). echo "${array[@]}" prints the elements of the array separated by spaces. Then the function multiple_values is called, and its output is captured in the result array. The $(...) syntax is used to execute the function and capture its output as an array. Finally, the script prints the individual values from the result array using array indexing (${result[0]}, ${result[1]}, and ${result[2]}).

return multiple values from bash function

This image demonstrates multiple values returned from a Bash function using an array.

3. Return Value as String

Like other programming languages, Bash does not support returning string values directly from the bash function. So to return the value as the string, use the echo command with the command substitution method. Follow the script to learn how to return string value from the function:

#!/bin/bash
greetings() {
  local name="$1"
  echo "Hello, $name!"
  echo "Good Morning"
}
message=$(greetings "John")  # Call the function and capture the return value
echo "$message"
EXPLANATION

Here, the Bash function named “greetings” takes a parameter “name”, echoes a greeting using the provided name, and then echoes a “Good Morning” message. message=$(greetings "John") calls the “greetings” function with the argument “John”. The output of the function (both lines of greeting) is captured in the variable “message” using command substitution ($(...)).

returning string from bash function

Upon executing the script, it displays the greeting message of the bash function.

4. Return Value as Boolean

There is no boolean type in the Bash function, but the exit status of a command can be used to represent a boolean value. Usually, a command with a successful execution returns an exit status of 0 (which is considered true), whereas a non-zero exit status is considered false. Here’s an example of a Bash function that returns a boolean value based on the file’s existence:

#!/bin/bash
function file_exists() {
  file_path="$1"
  [[ -f "$file_path" ]] && return 0  # Return 0 for true (file exists)
  return 1  # Return 1 for false (file doesn't exist)
}
if file_exists "file.txt"; then
  echo "File exists!"
else
  echo "File not found."
fi
EXPLANATION

This script checks if a file exists or not by creating a bash function named “file_exists”. The function takes one parameter, file_path, and checks if the file specified by file_path exists using the -f test in a conditional expression. If the file exists, the function returns 0 (true) and prints “File exists!”. If it doesn’t exist, it returns 1 (false) and echoes “File not found.”.

checking file existence using bash return value as boolean

Since “file.txt” is in the system, it shows “File exists”.

5. Return Values (Array) Using Global Variable

A global variable in bash is a variable declared outside of a function. It can be accessed and changed both inside and outside of the function. Because of this, there is a high chance of an unexpected error. Therefore, it is recommended to use local variables.

Now, see how the values are returned from the Bash function using a global variable:

#!/bin/bash
# Declare a global variable
declare -a numbers_array
function get_numbers() {
  # Assign values to the global variable
  numbers_array=(1 2 3)
}
# Call the function to populate the global variable
get_numbers
# Access elements from the global array
echo "The numbers are: ${numbers_array[@]}"
EXPLANATION

declare -a numbers_array declares a global array variable named numbers_array. The -a flag indicates that it’s an indexed array. The get_numbers function is created to assign values (1, 2, 3) to the global array variable. After calling the function, it prints the elements of the global array using ${numbers_array[@]}.

return values using global variables

As you can see, the values of the global array are shown in the terminal.

6. Return Values in Error Handling

Return values can be used to gracefully handle errors in the Bash function. In this example, the exit status is checked before performing the division operation using the $? variable. If the denominator is 0, the script will show an error message. Here’s the complete bash script for this:

#!/bin/bash
function division() {
  local numerator=$1
  local denominator=$2
  # Check if denominator is zero
  if [ "$denominator" -eq 0 ]; then
    echo "Error: Division by zero"
    return 1  # Return a non-zero value to indicate an error
  fi
  # Perform the division
  local result=$((numerator / denominator))
  echo "Result of division: $result"
  return 0  # Return 0 to indicate success
}
division 10 0  # This should fail
if [ $? -eq 0 ]; then
  echo "Division successful"
else
  echo "Error in division"
fi
EXPLANATION

The division function takes two parameters numerator and denominator. Before performing the division, it checks if the denominator is 0 or not. If the divisor is 0, the function prints an error message and returns a non-zero value to indicate failure. When the division is successful, the function prints the result and returns 0 to indicate success.

local result=$((numerator / denominator)) performs the division of the numerator by the denominator and stores the result in the result variable. division 10 0 calls the division function with arguments 10 and 0. The condition $? -eq 0 within the if statement checks the exit status of the last executed command. If the exit status is 0,  it prints “Division successful”; otherwise, prints “Error in division”.

return values in error handling

Since the denominator is 0, it displays an error message.

Common Issues with Bash Return Values

There are some problems that you may encounter while working with the bash function to return values. Let’s take a look at these problems and how to solve them.

Exceeding Return Value Limit

The return statement returns integer values between 0 and 255. Exceeding this range shows an unexpected result:

#!/bin/bash
function return_number() {
  return 265
}
return_number
echo $?

exceeding limit error

Here the value 9 is the remainder of 265 divided by 256. Actually, it resets to 0 after crossing the range. As an example, it yields 0 for 256, 1 for 257, and so forth. Likewise, it displays 9 for 265.

To avoid this problem and get the actual output, use the echo command or global variables:

#!/bin/bash
function return_number() {
  echo 265
}
result=$(return_number)
echo $result

The echo command with command substitution returns the value 265 as expected:

solution of exceeding limit error

Not Capturing Return Value

$? is used to capture the return value of the return statement. This must be used immediately after calling the function. If another command is called before the return value is captured, $? will be overwritten like this:

#!/bin/bash
function return_value() {
  return 25
}
return_value
echo "Welcome to Linuxsimply."
echo $?

not capturing return value error

To solve this issue, write the $? immediately after the function has been called to capture the return value properly:

#!/bin/bash
function return_value() {
  return 25
}
return_value
echo $?
echo "Welcome to Linuxsimply."

solution of not capturing return value error

As you can see in the image the actual return value 25 is displayed on the terminal.

Uninitialized Variable Error

If a variable is not initialized in the function, it can lead to an error:

#!/bin/bash
function return_variable() {
  local variable
  echo $variable
}
result=$(return_variable)
echo "Result: $result"

unset variable value error

Since the local variable value is unset in the function, it displays the empty result. To solve this problem, initialize the variable value first:

#!/bin/bash
function return_variable() {
  local variable=10
  echo $variable
}
result=$(return_variable)
echo "Result: $result"

solution of unset variable value error

Once the variable value has been set to 10, it will display the actual result.

Practice Tasks on Return Values from Bash Function

To improve your bash scripting skills and to understand how to return values from the bash function, practice the following:

  1. Write a Bash script that defines a function add_numbers which takes two parameters, adds them, and returns the integer result.
  2. Create a Bash script that defines a function is_even that takes a number as a parameter, and checks if it is even or odd.
  3. Make a script where a function named reverse_string takes a string as a parameter, reverses it, and returns the reversed string.
  4. Generate a script and create a function fibonacci that takes a number “n” as a parameter and returns the nth value in the Fibonacci sequence.

Conclusion

To conclude, I have covered the fundamentals of the bash function and how it returns values. Moreover, I have provided 6 examples of how to return values like integer, string, and array from the bash function. Some problems associated with returning values and their solutions are also explained. Lastly, don’t forget to complete the practice tasks. Have a great day!

People Also Ask

What is the return type and return value?

The return value is the value that a function produces when it finishes its execution. It is basically the result of the function and the data type of the return value is called the return type.

Do all functions return a value?

No. All functions don’t return a value. Whether a function returns value or not depends on the purposes of the function.

Can you call a void function?

Yes, you can call a void function. The void function is a function that does not return a value. So no return statement is required. At the end of a void function, it automatically returns to the caller.

Can a function only return once?

Actually, a function may have more than one return statement, but it returns a value the very first time it comes into contact with the return statement. When the function receives a return statement, it immediately exits and no more code is executed in the function. To execute multiple returns, you can use other approaches like using an array.

Can a function repeat itself?

Yes, a function in Bash can repeat itself using loops or recursive calls. Both for and while loops can be used for repeating a task within a function. Functions can also recursively call themselves.

Can functions return two values?

Yes, a function can return two values using a bash array and echo command. Here’s the example bash script:

#!/bin/bash
function return_two_values() {
local value1="First"
local value2="Second"
# Return values using an array
echo "$value1 $value2"
}
# Call the function and capture the result in an array
result=($(return_two_values))
# Access individual values
value1="${result[0]}"
value2="${result[1]}"
echo "Value 1: $value1"
echo "Value 2: $value2"

Modify the code by replacing the values you want to return.

Related Articles


<< Go Back to Bash Functions | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment