Chapter 9: Functions
As scripts increase in complexity, repeating code becomes a major source of bugs and maintenance overhead. Functions allow you to encapsulate logic into reusable blocks, making your scripts more modular, readable, and testable.
I. Defining and Invoking Functions
In Bash, functions are essentially "mini-scripts" that run within the same process as your main script.
1. The Two Syntaxes
While both are valid, the first one is the standard POSIX style and is generally preferred.
# Style 1: POSIX (Preferred)
my_func() {
echo "Hello"
}
# Style 2: Bash-specific
function my_func {
echo "Hello"
}
II. The Execution Pipeline
1 = "Jane"</text><text x="240" y="110" font-family="monospace" font-size="10" fill="#1e40af">echo "Hello 1"
III. Arguments and Scoping
1. Positional Parameters
Functions use the same variables as the main script to access arguments:
$1,$2... : First, second arguments.$#: Count of arguments.$*or$@: All arguments.
2. The local Keyword
By default, all variables in a shell script are Global. To avoid accidentally overwriting a variable in the main script, you must use the local keyword inside functions.
#!/usr/bin/env bash
NAME="Global User"
update_user() {
local NAME="Internal Admin" # Only exists inside this function
echo "Inside: $NAME"
}
update_user
echo "Outside: $NAME" # Still prints "Global User"
IV. Return Values vs. Output
This is the most common point of confusion for beginners.
1. The return Command
The return keyword only sends an Exit Status (0-255). It is used to indicate success or failure, NOT to send data back.
2. Capturing Data (The "Echo" Pattern)
To return data (like a string or number), you echo the result inside the function and capture it using command substitution.
#!/usr/bin/env bash
calculate_area() {
local WIDTH=$1
local HEIGHT=$2
local AREA=$(( WIDTH * HEIGHT ))
echo "$AREA" # This is the "return value"
}
# Capture the output
RESULT=$(calculate_area 10 5)
echo "Area is $RESULT"
V. Recursive Functions
Bash functions can call themselves. This is useful for processing hierarchical data like directory trees.
#!/usr/bin/env bash
factorial() {
if (( $1 <= 1 )); then
echo 1
else
local prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
echo "Factorial of 5 is $(factorial 5)"
In the next chapter, we'll learn how to manipulate large amounts of text using Grep, Sed, and Awk.