Returning Values from Functions In Bash

In Bash, you can return values from functions using the return statement. The return statement allows you to specify an exit status or a value that will be available to the caller of the function. Here’s an example:


add_numbers() {
    local sum=$(( $1 + $2 ))
    return $sum

# Calling the function and capturing the return value
add_numbers 5 3

echo "Sum: $result"

In this example, the add_numbers function takes two arguments, 5 and 3, and calculates their sum. The local keyword is used to declare a local variable sum within the function, which holds the calculated sum. The return statement is used to return the value of sum.

When the function is called with add_numbers 5 3, the return $sum statement will set the exit status of the function to the value of sum, which is 8 in this case. The return value can be accessed using the special variable $?.

The next line of code captures the return value of the function in the variable result. Finally, the script prints the value of result, which gives the sum:

Sum: 8

By using the return statement, you can pass values from a function back to the calling code. This allows you to perform calculations or tasks within the function and retrieve the results in the main script for further processing.

Leave a Comment

Your email address will not be published. Required fields are marked *