Skip to content

Functions

Function Definition and Invocation

Functions are essential for organizing BASH scripts into reusable, modular components. They allow you to encapsulate logic, reduce redundancy, and improve maintainability. This section covers how to define, invoke, and pass arguments to functions in BASH.


Defining Functions

A function is defined using the function keyword or parentheses syntax. The body of the function is indented for readability, though BASH does not enforce this.

# Syntax 1: Using 'function' keyword
function greet {
    echo "Hello, $1!"
}

# Syntax 2: Parentheses syntax (more common)
print_info() {
    echo "System info: $HOSTNAME"
}

Functions are not executed immediately when defined. Instead, they are loaded into memory and invoked explicitly.


Invoking Functions

To call a function, use its name followed by parentheses. Arguments are passed as positional parameters.

# Example 1: No arguments
greet

# Example 2: With arguments
add_numbers 3 5

Passing Arguments

Arguments are accessed via special variables $1, $2, ..., $n (where n is the number of arguments). The special variables $# and $* provide metadata about the arguments.

# Function definition
calculate_sum() {
    local sum=$(( $1 + $2 ))
    echo "Sum: $sum"
}

# Function invocation
calculate_sum 10 20
# Output: Sum: 30

For variadic arguments (multiple inputs), use $* or $@:

greet_all() {
    for name in "$@"; do
        echo "Hello, $name!"
    done
}

greet_all Alice Bob Charlie
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!

Scope and Variable Lifetime

By default, variables inside a function are global unless declared with local. Use local to restrict scope and avoid unintended side effects.

# Global variable
count=0

increment() {
    count=$(( count + 1 ))
}

increment
echo "Count: $count"  # Output: Count: 1

# Local variable
double() {
    local value=$1
    echo "Double: $(( value * 2 ))"
}

double 5
# Output: Double: 10

Error Handling and Best Practices

  • Use return to exit functions with status codes (0 for success, non-zero for errors).
  • Validate inputs to prevent unexpected behavior.
  • Avoid polluting the global namespace by using local variables.
check_file() {
    if [ -f "$1" ]; then
        echo "File exists: $1"
        return 0
    else
        echo "File not found: $1"
        return 1
    fi
}

check_file /etc/passwd || echo "Error: File missing!"

Key takeaways

  • Define functions using function name { ... } or name() { ... }.
  • Invoke functions with function_name [arguments].
  • Pass arguments via $1, $2, etc., and use $#/$* for metadata.
  • Use local to limit variable scope and prevent namespace conflicts.
  • Handle errors with return and validate inputs for robustness.