Functions and Script ArchitectureLesson 3.1
How to write and call Bash functions
function declaration syntax, calling functions, return values, return vs exit, function arguments $1 $2, local variables, function scope, overriding built-ins
Functions in Bash
Bash functions group commands under a name. They use the same argument system as scripts โ $1, $2, $@ โ but scoped to the function call.
#!/usr/bin/env bash
# Declaration
greet() {
local name="$1" # local: stays inside the function
echo "Hello, $name"
}
# Call
greet "Alice"
greet "Bob"Return Values
Bash functions don't return values like most languages. return N sets the exit code (0โ255). To pass data out, use stdout and capture with $().
get_timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}
log() {
local level="$1"
local message="$2"
local ts
ts=$(get_timestamp)
echo "[$ts] [$level] $message"
}
log "INFO" "Script started"
log "ERROR" "Connection failed"Return Status from Functions
file_exists() {
[[ -f "$1" ]] # exit code of [[ ]] becomes function's exit code
}
if file_exists "/etc/hosts"; then
echo "File found"
fiAlways declare variables inside functions as local. Without local, you're writing to the global scope, causing subtle bugs when functions are called multiple times or in loops.
