Bash Function Return Value
Last updated
Last updated
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.
Let's understand return values from the bash function with examples.
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 statementfunction
test_return_default() { echo
"This should return 0, i.e. the status of echo command"}
## Explicitly return 1function
test_return_explicit_status() { echo
"The function failed during execution!" return
1}
test_return_defaultecho
$?
echo
""
test_return_explicit_statusecho
$?
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.
$ cat
returnUsingEcho.sh#!/bin/bash
## Echo the output stringfunction
func_do_two_plus_three() {
echo
"The result is $((2+3))"}
## Echoed string is assigned to the result variableresult=$(func_do_two_plus_three)echo
$result
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 Bashfunction
func_do_multiple_math() { result1=$((2+3)) result2=$((4+7))}
func_do_multiple_math
## Access the global variablesecho
"The result 1 is $result1"echo
"The result 2 is $result2"
Although this works, it is not considered a good programming practice, especially in larger scripts.
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 paramsfunction
func_modify_passed_params() { local
lresult1=$1 local
lresult2=$2
eval
$lresult1=$((2+3)) eval
$lresult2=$((4+7))}
func_modify_passed_params result1 result2echo
"The result 1 is $result1"echo
"The result 2 is $result2"
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 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.
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=5denominator=0
## Invalid arithmeticresult=$(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=6denominator=0
## Invalid arithmeticresult=$(do_perform_division numerator denominator)
if
[[ $? -eq
1 ]]; then echo
-e "Denominator should not be 0 for performing division\n"fi
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.
A single value can be easily returned from a function using the command which directs the output to the . This value can be assigned to a variable in the caller.
A better way to return multiple values is to to the function and have local variables store the name of these passed parameters.
This concept of applies to bash scripts in general but in this section let’s see how we can handle errors with the bash functions.