Lesson 5 of 14 · 15m
Functions, getopts, and Exit Codes
Functions return statuses not values, the getopts shape for real flags, and which exit codes mean what.
A Bash function does not return a value. return sets an exit status — an integer, 0 to 255 — and anything past 255 wraps around. add() { return $(( $1 + $2 )); } returns 0 for add 128 128 and the person who wrote it spends an afternoon learning about exit codes. The language you're thinking of has return values; Bash has process statuses and stdout.
How functions actually communicate
Functions run in the current shell — no fork, no copy. Two real channels back to the caller:
# 1. stdout, captured with $()
current_release() {
readlink -f /srv/app/current # prints the answer
}
rel=$(current_release)
# 2. a global, because scoping says so
result=""
compute() { result="done: $1"; }
compute a; echo "$result"Rule of thumb: a function that produces data prints it; a function that does something returns a status. Mixing them — printing progress and the answer to the same stdout — corrupts the $( ) capture. Logs and prompts go to stderr: echo "deploying $rel" >&2.
local limits scope — but Bash scoping is dynamic: a function sees its caller's locals, not just globals. f() { local x=1; g; }; g() { echo "$x"; } prints 1. Keep helper variables local, and name your real outputs distinctively.
return only works inside a function (or a sourced file); exit kills the whole script from anywhere. A function that hits a fatal condition and can't return a meaningful status should exit 1 — or print to stderr and return 1 and let the caller decide. Pick one convention per script.
Exit statuses are a protocol
cmd; echo $? # 0 = success, non-zero = failure class1— generic failure.2— shell misuse (bad options, syntax).126— found but not executable.127— command not found.128+n— killed by signal n.130= SIGINT (128+2),143= SIGTERM (128+15),137= SIGKILL.timeoutreturns124when it kills the command.grepreturns1for "no match" — a findable status, not an error.- sysexits.h reserves 64–78 for meanings:
EX_USAGE64,EX_DATAERR65,EX_OSERR71. Scripts that adopt them are easier to alert on — a64means "you called me wrong", not "the world is broken".
exit "$?" preserves the incoming status instead of resetting it; the status at EXIT-trap time is in $? and is what the script actually returns.
getopts: flags a teammate can discover
Hand-rolled $1 parsing rots at flag three. getopts is the builtin:
usage() { echo "usage: $0 [-n] [-t seconds] [-o outdir] target" >&2; }
dry_run=0; timeout=300; outdir="./out"
while getopts ":nt:o:h" opt; do
case $opt in
n) dry_run=1 ;;
t) timeout=$OPTARG ;;
o) outdir=$OPTARG ;;
h) usage; exit 0 ;;
:) echo "-$OPTARG requires an argument" >&2; usage; exit 64 ;;
\?) echo "unknown option -$OPTARG" >&2; usage; exit 64 ;;
esac
done
shift $((OPTIND - 1))
[[ $# -eq 1 ]] || { usage; exit 64; }
target=$1- The leading
:in:nt:o:hsilences getopts' own errors so yourcaseprints readable ones.nis a flag;t:ando:take arguments. OPTARGholds the option's argument;OPTINDtracks position soshift $((OPTIND-1))leaves only positional args in$@.getoptsdoesn't do--longoptions.getopt(1)does, at the cost of an external binary and re-parsing — worth it when your script has users, not worth it for a cron job.--ends options for the caller:script.sh -- -weird-namelets a positional arg start with a dash.
Structure that survives contact
#!/usr/bin/env bash
set -euo pipefail
main() {
local target=$1
# ... real work, one level of indentation ...
}
main "$@"Wrapping everything in main means a partially-downloaded script piped into bash can't execute — the call at the bottom is the only thing that runs, and it only runs on a complete parse. It's the difference between curl | sh doing nothing and doing half.
Try this
Write deploy.sh with getopts flags -e env (default staging), -n dry-run, and a required positional version. Have -e prod require an extra -y confirm flag. Then check $? after calling it with a bad flag — it should be 64, not 1.
Pitfalls
local var=$(cmd)maskscmd's failure — thelocalbug from lesson 1 lives here too.shiftwith no argument count errors past$#underset -u-adjacent misuse; compute fromOPTINDor guard$#.returnfrom a function invoked as$(fn)sets the subshell's status — the caller sees it only through the assignment's$?.exitinside a function that's called in$( )kills the subshell, not your script — the capture just ends early. Test assumptions about "fatal" in both contexts.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Red Hat Called This Bug a 5.9. Two Weeks Later It Was a 9.8.
CVE-2026-98432 is a use-after-free in the IPv4 TCP handshake, reachable by anybody who can reach a listening port, sitting in the kernel since 4.4. Red Hat scored it 5.9 moderate and deferred the fix. Then 8.1. Then 9.8.
Self-Host OpenClaw: VPS Setup to Production (2026)
Self-host OpenClaw from zero to production. Server provisioning, SSH lockdown, Docker, reverse proxy, Fail2ban, performance tuning, and full backup strategy in one guide.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.