Functions

Defining functions, arguments, local variables, returning data and status codes.

Functions make scripts readable and reusable. In Bash they behave like small commands: they take positional arguments, print their results to standard output and report success or failure through their return status.

Functions in practice

Inside a function $1, $2 ... are its own arguments; shift drops the first one and $* is the rest.

local keeps variables private to the function.

count_level returns data by printing it; the caller captures it with $(...).

has_errors returns the status of its last command, so it can be used directly in if.

${1:-engineer} substitutes a default when the argument is missing.

Notes

count() { total=5; } # total leaks out count() { local total=5;...; }

Variables in Bash functions are global unless declared local, so they can silently overwrite the caller's variables.

How does a Bash function return a string?

By printing it (echo/printf); the caller captures it with result=$(func args).