Functions
Prerequisites: Script arguments, Conditionals: if and tests
A function is a named group of commands you can run like a command. Functions keep scripts organized and avoid repeating code.
Real-world analogy: a function is a recipe card. Write it once, then say "make pancakes" whenever you need them.
Syntax
name() {
commands
}
Example
greet() {
echo "Hello, $1!"
}
greet "Ada"
greet "Linus"
Expected output
Hello, Ada!
Hello, Linus!
- A function is defined before it's used, then called by name, like any command.
- Inside a function,
$1,$2,$#, and"$@"are the function's arguments, not the script's.
A useful pattern: logging helpers
log() { echo "[INFO] $*"; }
warn() { echo "[WARN] $*" >&2; }
die() { echo "[ERROR] $*" >&2; exit 1; }
log "Starting backup"
warn "Disk is 85% full"
[[ -d /definitely/missing ]] || die "Backup folder not found"
log "This line never runs"
[INFO] Starting backup
[WARN] Disk is 85% full
[ERROR] Backup folder not found
$* joins all arguments into one string — right for messages. die
prints an error and stops the script, which makes checks short and
readable: command || die "message".
Organizing a script with functions
A common layout: define functions first, then call a main function at
the bottom with all the script's arguments:
usage() {
echo "Usage: backup.sh <source> <destination>"
}
main() {
if (( $# != 2 )); then
usage
return 1
fi
echo "Backing up $1 to $2"
}
main "photos" "/mnt/backup"
Backing up photos to /mnt/backup
Reading from main down, the script's flow is clear at a glance.
Common mistakes
- Calling a function before its definition — Bash reads scripts top to
bottom, so it isn't known yet:
command not found. - Expecting
exitinside a function to only leave the function.exitends the whole script; usereturnto leave just the function.
Practice
Write a function square that prints the square of its first argument,
and call it with 7.
Show solution
square() {
echo $(( $1 * $1 ))
}
square 7
49