Skip to content

Latest commit

 

History

History
91 lines (58 loc) · 2.72 KB

02.Passing_arguments_to_functions.md

File metadata and controls

91 lines (58 loc) · 2.72 KB

Passing Arguments to Functions in Linux Scripting

Passing arguments to functions in Linux scripting allows you to make your functions more flexible and dynamic. By providing input parameters, you can customize the behavior of your functions based on specific values. This tutorial will guide you through the process of passing arguments to functions in a Linux environment.

Basic Syntax

The basic syntax for defining a function with parameters is as follows:

function_name() {
    local parameter1=$1
    local parameter2=$2

    # Function code using parameters
    # ...
}

Here, parameter1 and parameter2 are placeholders for the actual parameters that will be passed when calling the function.

Example Function with Arguments

Let's create a simple function that takes two numbers as arguments and prints their sum:

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

    echo "The sum of $num1 and $num2 is: $sum"
}

Calling Functions with Arguments

To call a function with arguments, provide the values when invoking the function:

add_numbers 5 3

This will output: The sum of 5 and 3 is: 8

Variable Scope in Functions

Parameters are treated as local variables within the function. They do not interfere with variables outside the function unless explicitly declared as global using the local keyword.

global_var="I am global"

print_global_and_local() {
    local local_var="I am local"
    echo "Inside function: local_var - $local_var, global_var - $global_var"
}

print_global_and_local

echo "Outside function: global_var - $global_var"

This will output:

Inside function: local_var - I am local, global_var - I am global
Outside function: global_var - I am global

Variable Positional Parameters

In addition to specifying parameters explicitly, you can use the special variables $@ and $* to access all passed arguments within the function:

print_all_arguments() {
    echo "All arguments: \$@ - $@, \$* - $*"
}

print_all_arguments arg1 arg2 arg3

This will output: All arguments: $@ - arg1 arg2 arg3, $* - arg1 arg2 arg3

Conclusion

Passing arguments to functions enhances the flexibility and usefulness of your scripts. By incorporating parameters, you can create more generic and adaptable functions that cater to a variety of scenarios. Understanding variable scope and leveraging special variables further enriches your scripting capabilities. Apply these concepts in your Linux scripts to build robust and versatile solutions.