Bash Function Return Value

Written by: Madhur Batra   |   Last updated: March 19, 2023

In Bash, functions do not support returning values like in other programming languages. Instead, the return value of a function is its exit status, a numeric value indicating success or failure. A zero exit status indicates success, while a non-zero exit status indicates failure.

Return values from a Bash function

Let's understand return values from the bash function with examples.

Returning a status code

Although there exists a return statement, it can only be used to explicitly set the exit status code of a function. If a return statement is not specified in a Bash function, the exit status code is set equal to the status code of the last command executed in the function.

Consider the following script:

$ cat returnStatus.sh
#!/bin/bash

## Return status of last statement
function test_return_default() {
       echo "This should return 0, i.e. the status of echo command"
}

## Explicitly return 1
function test_return_explicit_status() {
       echo "The function failed during execution!"
       return 1
}

test_return_default
echo $?

echo ""

test_return_explicit_status
echo $?
return status code 0

On executing the script, we see the following:

  • Function test_return_default returns the status of the echo statement i.e. 0.
  • In the function test_return_explicit_status, the status is explicitly returned using the return command.
  • The status code is set in the $? variable and can be accessed by the caller to make decisions.

Return a single value using the echo command

A single value can be easily returned from a function using the echo command which directs the output to the standard out. This value can be assigned to a variable in the caller.

$ cat returnUsingEcho.sh
#!/bin/bash

## Echo the output string
function func_do_two_plus_three() {

       echo "The result is $((2+3))"
}

## Echoed string is assigned to the result variable
result=$(func_do_two_plus_three)
echo $result
bash function return single value

Return multiple values using global variables

An easy way to return multiple values from a function is to set global variables in the function and reference the variables after the function. 

$cat returnMultUsingGlobVar.sh
#!/bin/bash

## Set global variables `result1`, `result2` in the function
## By default variables have global scope in Bash
function func_do_multiple_math() {
       result1=$((2+3))
       result2=$((4+7))
}

func_do_multiple_math

## Access the global variables
echo "The result 1 is $result1"
echo "The result 2 is $result2"
return multiple values

Although this works, it is not considered a good programming practice, especially in larger scripts.

Return using function parameters

A better way to return multiple values is to pass parameters to the function and have local variables store the name of these passed parameters.

Then, we can modify the passed parameters to store the result of the functions.

Consider the following script:

$cat returnUsingPassedParams.sh
#!/bin/bash

## Local variables store the name of passed params
function func_modify_passed_params() {
       local lresult1=$1
       local lresult2=$2

       eval $lresult1=$((2+3))
       eval $lresult2=$((4+7))
}

func_modify_passed_params result1 result2
echo "The result 1 is $result1"
echo "The result 2 is $result2"
Return using function parameters

On executing the script:

  • func_modify_passed_params result1 result2 passes the parameters result1, and result2 to the function.
  • local lresult1=$1 assigns the local variable lresult1 equal to the name of the first parameter i.e. result1.
  • eval $lresult1=$((2+3)) sets the variable referenced by lresult1 i.e. result1=5.

Error handling

Error handling is a very important concept in any programming language. It helps to handle errors gracefully and not terminate the program on running an erroneous command.

This concept of error handling applies to bash scripts in general but in this section let’s see how we can handle errors with the bash functions.

Consider the following bash function which attempts to perform division on the passed parameters.

$cat errorHandlingInBashFunc.sh
#!/bin/bash

function do_perform_division() {
       echo $((numerator/denominator))
}


numerator=5
denominator=0

## Invalid arithmetic
result=$(do_perform_division numerator denominator)

On executing the script, 

  • It encounters a runtime error since the denominator=0 results in division by 0 which is invalid. 
  • The script immediately terminates and prints the error to the user.

We can handle this error gracefully by pre-checking the denominator and returning from the function after setting the status code.

Using the returned status code in $? variable, we can print a useful message for the user.

$cat errorHandlingInBashFunc.sh
#!/bin/bash

function do_perform_division() {
       if [[ $denominator -eq 0 ]]; then
               return 1
       fi
       echo $((numerator/denominator))
}

numerator=6
denominator=0

## Invalid arithmetic
result=$(do_perform_division numerator denominator)

if [[ $? -eq 1 ]]; then
       echo -e "Denominator should not be 0 for performing division\n"
fi

Conclusion

Although Bash does not support returning values directly, there are other methods to return values from a function.

  • For simple functions, returning a single result, it is simpler to use the echo command to direct the output to a stdout and assign the result to a variable in the caller.
  • For functions returning 2 or more results, modifying the global variables in the function is a possible solution but this quickly gets cumbersome to deal with, especially in larger scripts.
  • Passing and modifying the parameters in a large function is a better method when dealing with multiple results.
  • Bash functions can return custom status codes which can be used to gracefully handle errors in the scripts and make decisions.

About The Author

Madhur Batra

Madhur Batra

Madhur Batra is a highly skilled software engineer with 8 years of personal programming experience and 4 years of professional industry experience. He holds a B.E. degree in Information Technology from NSUT, Delhi. Madhur’s expertise lies in C/C++, Python, Golang, Shell scripting, Azure, systems programming, and computer networking. With a strong background in these areas, he is well-equipped to tackle complex software development projects and contribute effectively to any team.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment