Logo

Bash Scripting Guide: Functions

This section covers the creation and usage of functions in Bash scripts.

Table of Contents

  1. Introduction to Functions
  2. Defining Functions
    1. Basic Syntax
    2. Function Arguments
    3. Return Values
  3. Calling Functions
  4. Scope and Variables
    1. Local Variables
    2. Global Variables
  5. Examples
  6. Best Practices

1. Introduction to Functions

In Bash scripting, functions allow you to group code into reusable blocks. They enhance code readability and maintainability.

2. Defining Functions

2.1 Basic Syntax

To declare a function, use the following syntax:


function_name() {
    # function body
    echo "Hello, I am a function!"
}

2.2 Function Arguments

Functions can accept arguments:


greet_user() {
    echo "Hello, $1!"
}

# Call the function with an argument
greet_user "John"

2.3 Return Values

Bash functions can return values using return:


add_numbers() {
    local result=$(( $1 + $2 ))
    return $result
}

# Call the function and capture the result
add_numbers 5 3
sum=$?
echo "The sum is: $sum"

3. Calling Functions

Call a function by using its name:


function_name

4. Scope and Variables

4.1 Local Variables

Use local to declare variables with local scope:


calculate_square() {
    local squared=$(( $1 * $1 ))
    echo $squared
}

4.2 Global Variables

Variables declared outside functions have global scope.


global_var="I am global"

print_global() {
    echo $global_var
}

5. Examples

5.1 Simple Function


greet() {
    echo "Hello, world!"
}

# Call the function
greet

5.2 Function with Arguments


calculate_product() {
    local product=$(( $1 * $2 ))
    echo "The product is: $product"
}

# Call the function with arguments
calculate_product 4 6

6. Best Practices


Continue to Part 6: input Output.

Go back to Bash Scripting Guide.

Visit other Developer Guides.