Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Return values from a Bash function
  • Error handling
  • Conclusion

Bash Function Return Value

PreviousHow to Pass all Arguments in Bash ScriptingNextBash Loop Through Lines in a File

Last updated 1 year ago

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 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.

Return a single value using the echo command

$ 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

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 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.

Return using function 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 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

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

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.

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.

echo
standard out
pass parameters
error handling
Return using function parameters
return multiple values
return status code 0
bash function return single value