Skip to content
Bash

Functions

Function definition and parameters.

By EZ4Code Team
bashfunction

Code

#!/bin/bash

# Basic function
greet() {
    echo "Hello, $1!"
}
greet "World"  # Hello, World!

# With return value
add() {
    local sum=$(( $1 + $2 ))
    echo $sum
}
result=$(add 3 5)
echo "3 + 5 = $result"

# Return status code
is_even() {
    if [ $(($1 % 2)) -eq 0 ]; then
        return 0  # true
    else
        return 1  # false
    fi
}

if is_even 4; then
    echo "4 is even"
fi

# Local variable
counter() {
    local count=0  # Local variable
    ((count++))
    echo $count
}

# Default parameter
greet_user() {
    local name=${1:-Guest}  # Default value
    local greeting=${2:-Hello}
    echo "$greeting, $name!"
}
greet_user  # Hello, Guest!
greet_user "Alice" "Hi"  # Hi, Alice!

# Variadic parameter
sum_all() {
    local total=0
    for num in "$@"; do
        ((total += num))
    done
    echo $total
}
sum_all 1 2 3 4 5  # 15

# Recursion
factorial() {
    if [ $1 -le 1 ]; then
        echo 1
    else
        local prev=$(factorial $(($1 - 1)))
        echo $(($1 * prev))
    fi
}
factorial 5  # 120

# Function reference
func=greet
$func "from variable"

Explanation

Bash functions are defined with name(); local declares local variables; return returns a status code; echo outputs results.

More Bash Snippets