BudiBadu Logo
Samplebadu

Shell Script by Example: Functions

Bash 5.x

Creating reusable code blocks with this sample code showing function definition syntax, accessing arguments via positional parameters, local variable scope, return statements for exit status, and capturing function output using command substitution.

Code

#!/bin/bash

# Function definition
greet() {
    local name=$1 # Local variable
    echo "Hello, $name"
}

# Calling function
greet "Alice"

# Function with return status
check_file() {
    if [ -f "$1" ]; then
        return 0 # Success
    else
        return 1 # Failure
    fi
}

if check_file "/etc/hosts"; then
    echo "Hosts file found"
fi

# Capturing output (fake return value)
get_sum() {
    echo $(($1 + $2))
}

total=$(get_sum 10 20)
echo "Total: $total"

Explanation

Functions organize scripts into reusable, modular chunks of code. You define them using name() { ... } or function name { ... } syntax. Inside a function, arguments are accessed through positional parameters $1, $2, etc., identical to how scripts receive command-line arguments. The special variable $# contains the argument count, and "$@" expands to all arguments as separate quoted strings.

Variables defined inside functions are global by default, which can lead to unintended side effects and variable pollution. Always declare function-local variables using the local keyword to ensure they're only accessible within that function and its children. This prevents accidentally overwriting variables in the calling scope and makes functions more predictable and testable.

Bash functions don't return values in the traditional programming sense. The return statement only sets the function's exit status (0-255), where 0 conventionally indicates success and non-zero indicates failure. This exit status is accessible via $? immediately after the function call. To "return" actual data, functions typically write to standard output using echo, which the caller captures using command substitution like result=$(function_name args). This pattern is fundamental to Bash function design.

Code Breakdown

5
local name=$1 creates function-scoped variable from first argument.
10
Functions are called like commands, without parentheses around arguments.
15
return 0 sets exit status to 0 (success) for conditional checks.
30
$(get_sum 10 20) captures function's stdout output as return value.