Functions and Return Values
Defines and uses Bash functions with local variables, return values, argument passing, and recursive calls for modular and reusable script logic.
Code
#!/usr/bin/env bash
set -euo pipefail
# Basic function
greet() {
local name="${1:-World}"
echo "Hello, $name!"
}
# Function returning a value via stdout
calculate_area() {
local width=$1
local height=$2
echo $(( width * height ))
}
# Function with return status
is_even() {
local num=$1
(( num % 2 == 0 ))
}
# Recursive function: factorial
factorial() {
local n=$1
if (( n <= 1 )); then
echo 1
else
local prev
prev=$(factorial $(( n - 1 )))
echo $(( n * prev ))
fi
}
# Main execution
greet "Alice"
greet
area=$(calculate_area 5 10)
echo "Area: $area"
if is_even 42; then
echo "42 is even"
fi
fact=$(factorial 5)
echo "5! = $fact"How the snippet works
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to greet, chained so each stage’s output feeds the next.
4 helper functions (greet, calculate_area, is_even and factorial) keep the repeated logic out of the main flow.
The script leans on parameter expansion 1 time, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
The key statements that remain
prev=$(factorial $(( n - 1 )))
area=$(calculate_area 5 10)
fact=$(factorial 5)
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `greet` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.