Functions
Group reusable logic with shell functions.
Defining functions
hello() {
echo "Hello, $1"
}
hello "Ada"
Names share the global namespace; prefer unique prefixes for libraries.
Local variables and scope
inc() {
local x=${1:-0}
((x++))
echo "$x"
}
count=$(inc 41)
local restricts scope inside a function.
Returning values
- Use
echo/printfto output data and capture with command substitution - Use
return <code>for success/failure (0–255)
validate() { [[ $1 =~ ^[0-9]+$ ]] || return 1; }
if validate "$age"; then echo ok; fi
Arguments and $@
myfn() {
for arg in "$@"; do echo "$arg"; done
}
Sourcing and libraries
# lib.sh
say() { echo "[$(date +%T)] $*"; }
# script.sh
source ./lib.sh
say "start"
Error handling
Combine with set -euo pipefail and check statuses. Use traps for cleanup.
trap 'echo cleanup; rm -f "$tmp"' EXIT
Summary
- Functions return data via stdout and status via
return - Use
local, quote args, and prefer sourcing for reuse