Skip to content

Latest commit

 

History

History
93 lines (62 loc) · 2.46 KB

03.Returning_values_from_functions.md

File metadata and controls

93 lines (62 loc) · 2.46 KB

Returning Values from Functions in Linux

Returning values from functions in Linux scripting allows you to capture and utilize the results of a function in the main body of your script. This tutorial will guide you through the process of returning values from functions and using them effectively in a Linux environment.

Basic Syntax

The basic syntax for defining a function that returns a value is as follows:

function_name() {
    # Function code
    # ...
    return value
}

Here, value is the result that the function will return. It can be a constant, variable, or the result of an expression.

Example Function with Return Value

Let's create a simple function that calculates the square of a number and returns the result:

calculate_square() {
    local num=$1
    local square=$((num * num))

    # Returning the square value
    return $square
}

Calling Functions and Capturing Return Values

To call a function and capture its return value, you can use the $? variable:

calculate_square 4
result=$?
echo "The square is: $result"

This will output: The square is: 16

Using Return Values in Expressions

Return values can be directly used in expressions or assigned to variables:

calculate_sum() {
    local num1=$1
    local num2=$2
    local sum=$((num1 + num2))

    # Returning the sum value
    return $sum
}

calculate_sum 8 5
total=$(calculate_sum 8 5)
echo "The total sum is: $total"

This will output: The total sum is: 13

Handling Multiple Return Values

If you need to return multiple values, you can utilize global variables or print the values to standard output and capture them using command substitution:

return_multiple_values() {
    local value1="Hello"
    local value2="World"

    # Printing values to standard output
    echo "$value1 $value2"
}

result=$(return_multiple_values)
echo "Returned values: $result"

This will output: Returned values: Hello World

Conclusion

Returning values from functions is a powerful feature in Linux scripting, enabling you to encapsulate logic and provide meaningful results to the rest of your script. By understanding the basic syntax, calling functions, and capturing return values, you can create more versatile and efficient scripts. Apply these concepts to enhance the modularity and usability of your Linux scripts.


Next | Arrays