Intermediate โฑ 20 min Lesson 8 of 13

โš™๏ธ Functions

Define reusable functions, pass arguments, and handle return values.

Functions in Bash

Functions let you group commands into reusable blocks. They make your scripts more organized, readable, and maintainable โ€” just like functions in any other programming language.

Defining Functions

Bash supports two syntax styles for defining functions:

bash
# Style 1: function keyword
function greet {
    echo "Hello, World!"
}

# Style 2: parentheses (more portable, POSIX-compatible)
greet() {
    echo "Hello, World!"
}

# Call the function (no parentheses needed)
greet
๐Ÿ’ก Tip: The parentheses syntax greet() { ... } is preferred because it works in all POSIX-compatible shells, not just Bash.

Function Arguments

Functions receive arguments through positional parameters โ€” the same way scripts receive command-line arguments.

bash
greet() {
    echo "Hello, $1!"         # $1 = first argument
    echo "You are $2 years old" # $2 = second argument
}

greet "Alice" 30
# Output:
# Hello, Alice!
# You are 30 years old

# Special parameters:
show_args() {
    echo "Number of args: $#"   # $# = argument count
    echo "All args: $@"         # $@ = all arguments as separate words
    echo "All args: $*"         # $* = all arguments as single string
    echo "Script/function name context: $0"
}

show_args one two three

Return Values vs Echo

In Bash, return sets an exit code (0โ€“255), not a data value. To "return" actual data, use echo and capture it with command substitution.

bash
# return sets an exit code (0 = success, non-zero = failure)
is_even() {
    if (( $1 % 2 == 0 )); then
        return 0   # success (true)
    else
        return 1   # failure (false)
    fi
}

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

# To return data, echo it and capture with $()
get_greeting() {
    echo "Hello, $1!"
}

message=$(get_greeting "Alice")
echo "$message"   # Hello, Alice!
โš ๏ธ Warning: return only accepts integers from 0 to 255. If you need to return a string or a number outside this range, use echo and capture the output.

Local Variables

By default, variables inside functions are global. Use local to make them scoped to the function.

bash
my_function() {
    local my_var="I am local"
    global_var="I am global"
    echo "$my_var"
}

my_function
echo "$global_var"  # Works โ€” "I am global"
echo "$my_var"      # Empty โ€” local variables don't leak

Recursive Functions

Bash functions can call themselves. Here's a classic factorial example:

bash
factorial() {
    local n=$1
    if (( n <= 1 )); then
        echo 1
    else
        local prev=$(factorial $((n - 1)))
        echo $((n * prev))
    fi
}

result=$(factorial 5)
echo "5! = $result"   # 5! = 120

Try It Yourself

Terminal

Summary

You've learned how to define functions with two syntaxes, pass arguments with $1, $2, etc., the difference between return (exit codes) and echo (data), local vs global variables, and recursion. Functions are the building blocks of clean, maintainable scripts.

๐Ÿงช Test Your Knowledge

Answer the questions below to check your understanding of this lesson.