Skip to content

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 class
  • 1 — 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.
  • timeout returns 124 when it kills the command. grep returns 1 for "no match" — a findable status, not an error.
  • sysexits.h reserves 64–78 for meanings: EX_USAGE 64, EX_DATAERR 65, EX_OSERR 71. Scripts that adopt them are easier to alert on — a 64 means "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:h silences getopts' own errors so your case prints readable ones. n is a flag; t: and o: take arguments.
  • OPTARG holds the option's argument; OPTIND tracks position so shift $((OPTIND-1)) leaves only positional args in $@.
  • getopts doesn't do --long options. 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-name lets 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) masks cmd's failure — the local bug from lesson 1 lives here too.
  • shift with no argument count errors past $# under set -u-adjacent misuse; compute from OPTIND or guard $#.
  • return from a function invoked as $(fn) sets the subshell's status — the caller sees it only through the assignment's $?.
  • exit inside 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.