As scripts grow past a screen or two, they get hard to read and the same blocks of code appear in several places. Functions fix both problems. A function is a named group of commands that you can call like any other command, with its own arguments and its own exit code. Well-named functions turn a script into something that reads like a checklist.
In simple words
- Function: a named block of commands you can call many times, like a mini script inside your script.
- local: keeps a variable inside the function, so it does not clash with the rest of the script.
- Return value: functions return an exit code (0 to 255). To return data, print it and capture the output.
- source: loads functions from another file into the current script.
Defining and calling a function
greet() { echo "Hello, $1"} greet Leelagreet "the platform team"- Define a function with
name() { commands; }. Thefunction name { … }form also works but is Bash-only; the first form is portable. - Define before you call. Bash reads a script top to bottom, so the definition must come first.
- Call it by name, like a command. No parentheses at the call site.
In the practice terminal you can define it on one line (note the spaces after { and the ; before }):
greet() { echo "Hello, $1"; }greet Leelagreet "the platform team"Hello, LeelaHello, the platform teamArguments
Inside a function, $1, $2, $# and "$@" refer to the function's arguments, not the script's:
show_args() { echo "got $# argument(s): $*"; echo "first is: $1"; }show_args web prod eu-west-1got 3 argument(s): web prod eu-west-1first is: web$0 stays the script name. Give arguments readable names at the top of the function:
deploy() { local app=$1 env=$2 version=${3:-latest} echo "Deploying $app:$version to $env"}local: keep variables inside
By default, every variable in Bash is global, even when it is set inside a function. That causes nasty bugs in longer scripts:
name=globalset_name() { name=changed; }set_nameecho "$name"changedThe function silently overwrote the script's variable. Declare function variables with local:
name=globalset_name() { local name=inside; echo "inside: $name"; }set_nameecho "outside: $name"inside: insideoutside: globalRule: every variable you create in a function should be local, unless you deliberately want to change a global.
Return values: exit codes
return N ends a function with exit code N (0–255), just like exit ends a script. That makes functions work naturally with if, && and ||:
is_known_host() { grep -q "$1" /etc/hosts; }if is_known_host web1; then echo "web1 known"; fiis_known_host mysql || echo "mysql not in hosts"web1 knownmysql not in hostsWithout an explicit return, a function returns the exit code of its last command, which here is grep -q. Explicit codes help when there are several outcomes:
check_disk() { local usage=$1 if (( usage >= 95 )); then return 2 # critical elif (( usage >= 85 )); then return 1 # warning fi return 0 # fine}Return values: output
return can only give a number. To give back text, have the function print it and capture it with $( ):
get_ip() { awk -v h="$1" '$2 == h {print $1}' /etc/hosts; }ip=$(get_ip web2)echo "web2 is at $ip"web2 is at 10.0.1.11This is the standard pattern. It means a function that returns text must not print anything else to stdout; send log messages to stderr with >&2 so they are not captured by accident:
get_version() { echo "looking up version..." >&2; echo "2.4.1"; }v=$(get_version)echo "version=$v"looking up version...version=2.4.1A logging helper
Almost every real script starts with a few small helpers. A logger is the most common:
log() { echo "[$(date +%H:%M:%S)] $*" >&2; }die() { log "ERROR: $*"; exit 1; }log "starting backup"[09:42:01] starting backupWith die, error handling becomes one readable line:
[[ -d $src ]] || die "source folder $src does not exist"cd "$dest" || die "cannot enter $dest"The main function pattern
Larger scripts put the top-level logic in a function called main and call it on the last line with all the script's arguments:
#!/usr/bin/env bashset -euo pipefail log() { echo "[$(date +%T)] $*" >&2; }die() { log "ERROR: $*"; exit 1; } usage() { echo "usage: $0 APP ENV" >&2 exit 2} deploy() { local app=$1 env=$2 log "deploying $app to $env" # … real work here …} main() { [[ $# -eq 2 ]] || usage deploy "$1" "$2" log "done"} main "$@"Why this helps:
- The script reads top-down: helpers, then the steps, then
mainas the table of contents. - All functions are defined before any run, so their order does not matter.
- Variables inside
maincan belocaltoo. - If the file is cut off while downloading (
curl … | bash), nothing runs until the last line arrives.
Sourcing functions from a library
Functions you use in many scripts can live in one file that each script sources:
printf 'log() { echo "[lib] $*"; }\nis_prod() { [[ $1 == prod ]]; }\n' > lib.shsource ./lib.shlog "loaded"is_prod prod && log "this is production"[lib] loaded[lib] this is productionsource runs the file in the current shell, so its functions become available. You will build a proper library layout in the final lesson.
Real-world scenario: health checks as functions
An SRE writes a check script where each check is a function that returns 0 or 1. The main loop runs them all and counts failures:
check_disk() { (( $(df --output=pcent / | tail -1 | tr -dc 0-9) < 85 )); }check_nginx() { systemctl is-active --quiet nginx; }check_api() { curl -fsS http://localhost:8080/health > /dev/null; } failed=0for check in check_disk check_nginx check_api; do if "$check"; then echo "PASS $check" else echo "FAIL $check" failed=$((failed + 1)) fidoneexit "$failed"Adding a new check is now one line, and the loop treats every check the same way. The exit code tells CI or a monitoring agent how many checks failed.
Common mistakes
- Calling before defining:
command not found. - Forgetting
local: functions overwrite globals with the same name. return "some text":returnonly takes a number. Echo text and capture it.- Printing logs to stdout in a function whose output is captured: the logs end up inside your variable.
- Missing
;or spaces in one-line functions:f() {echo hi}fails; writef() { echo hi; }. - Naming a function after a command like
lsortest: it silently replaces the command for the rest of the script.
Practice
- Write
square()that prints the square of its argument, and use it as$(square 7). - Write
is_even()that returns 0 for even numbers and 1 for odd, and use it in anif. - Write
count_errors()that takes a log file path and prints how many lines containERROR. Test it on/var/log/app/app.log. - Demonstrate the
localbug: set a globali=100, write a function that loops withfor i in 1 2 3withoutlocal, call it, and print$i. Then fix it.
Cheat sheet
name() { cmd; cmd; } define (before use)name arg1 arg2 call$1 $2 $# "$@" function argumentslocal var=value variable visible only insidereturn N exit code 0–255result=$(name args) capture printed outputecho "log" >&2 log without polluting outputdie() { echo "$*" >&2; exit 1; }main() { …; }; main "$@" structure larger scriptssource ./lib.sh load functions from a fileKey takeaways
- Functions are named groups of commands, called like any command, defined before use.
- They receive their own
$1,$2,"$@". - Use
localfor every variable inside a function. returngives an exit code forifand&&; echo text and capture it with$( )to return data.log,dieand amainfunction make even long scripts easy to read.