G
GuideDevOps
Lesson 6 of 15

Functions

Part of the Shell Scripting (Bash) tutorial series.

Defining Functions

Basic Function

# Method 1
function my_function() {
    echo "Hello from function"
}
 
# Method 2 (preferred in bash)
my_function() {
    echo "Hello from function"
}
 
# Call function
my_function

Function Arguments

greet() {
    echo "Hello, $1!"
    echo "Your age is $2"
}
 
# Call with arguments
greet "Alice" 30
greet "Bob" 25

Accessing Arguments

process_args() {
    echo "First: $1"
    echo "Second: $2"
    echo "All: $@"
    echo "Count: $#"
}
 
process_args arg1 arg2 arg3

Return Values

add_numbers() {
    local sum=$((1 + $2))
    return $sum          # Note: only 0-255
}
 
# Get return value
add_numbers 10 20
result=$?
echo "Result: $result"
 
# Better: use echo for larger values
add_better() {
    echo $((1 + $2))
}
 
result=$(add_better 10 20)
echo "Result: $result"

Local Variables

count=5             # Global variable
 
my_func() {
    local count=10  # Local variable
    echo "In function: $count"
}
 
my_func
echo "Outside: $count"   # Still 5

Function with Conditionals

check_file() {
    if [ -f "$1" ]; then
        echo "File exists: $1"
        return 0
    else
        echo "File not found: $1"
        return 1
    fi
}
 
if check_file "/etc/passwd"; then
    echo "Processing file..."
fi

Parameter Expansion in Functions

# Set default value
greet_user() {
    local name="${1:-Guest}"
    echo "Welcome, $name!"
}
 
greet_user                 # Welcome, Guest!
greet_user "Alice"        # Welcome, Alice!

Function Libraries

Create reusable library file (lib.sh):

# lib.sh
log_info() {
    echo "[INFO] $*"
}
 
log_error() {
    echo "[ERROR] $*" >&2
}
 
require_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "This requires root privileges"
        exit 1
    fi
}

Use in script:

source ./lib.sh
 
require_root
log_info "Starting backup..."

Array as Function Argument

print_array() {
    local -n arr=$1    # Reference to array
    for item in "${arr[@]}"; do
        echo "$item"
    done
}
 
my_array=("one" "two" "three")
print_array my_array

Practical Examples

Error Handling Function

error_exit() {
    echo "ERROR: $1" >&2
    exit "${2:-1}"
}
 
if [ ! -f "$config" ]; then
    error_exit "Config file not found" 2
fi

Retry Function

retry() {
    local max_attempts=3
    local count=0
    while [ $count -lt $max_attempts ]; do
        if "$@"; then
            return 0
        fi
        ((count++))
        sleep 2
    done
    return 1
}
 
retry curl https://example.com