Use it to reuse logic in scripts and shells, or when a function's result or exit code is wrong.
Functions
A Bash function groups commands under a name: name() { …; }. It takes arguments as $1, $2, $@, returns an exit status with return, and runs in the current shell.
1. type <name> — the function definition loaded?
2. Call it with set -x to trace.
3. Wrong result → is it using return for data instead of echo?
4. Global variable changed → add local.
5. Check $? after the call.
function defined → called with arguments → runs in the current shell → output written, status returned
For Shell & Bash → Functions, continue with the first unproven Topic check: Inspect function definition with the shell's own introspection and confirm which definition wins command resolution. If that boundary is healthy, advance to the adjacent check: Test positional parameters, empty arguments, local/global variable interactions and return statuses. Preserve the same host/time/identity scope and rerun the original workload before accepting recovery.
Continue only after interpreting the current observation.Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Operational evidence path Verify boundary
function definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behavior
Healthy evidence: function resolution, arguments, local/global effects, stdout and return status are all understood and caller behavior is verified.
Step 2 Verification and output interpretation Verify boundary
Existing fast checks for this Topic. - Inspect function definition with the shell's own introspection and confirm which definition wins command resolution.
- Test positional parameters, empty arguments, local/global variable interactions and return statuses.
- Identify intentional current-shell side effects such as cwd/options/traps/environment.
- Verify callers handle both stdout and return status correctly and that external subprocess boundaries are explicit.
Verification chain. function definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behavior
Step 3 Commands Verify boundary
greet() { echo "hi $1"; }
greet alice
declare -f greet
Step 4 Failure modes and next checks Narrow the fault
Suspicious evidence: a function unexpectedly changes cwd/options/globals, output is confused with return status, or dynamic scope modifies a caller variable.
Step 5 Common mistakes Narrow the fault
- Not using
localfor function variables.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
return only sets the exit status (0–255); output data with echo and capture it with $( ). Declare variables with local to avoid overwriting globals. Functions shadow commands of the same name.
bash -x script.sh— trace each expanded commandbash -n script.sh— syntax check onlyshellcheck script.sh— common bugs and quoting problemsecho $?— exit code of the last command
ReferenceWhat it is1 section · depth on demand
Core model
Functions are not external processes unless they explicitly spawn work. Understand dynamic variable visibility, local variables, return status, positional-parameter shadowing and side effects on current-shell state such as cd, umask, traps or options.
ReferenceImportant terms & boundaries5 sections · depth on demand
What this shows and what it does not
Function verification shows behavior in the current Bash state and tested arguments; it does not imply subprocess isolation or portability to other shells.
In depth
Shell functions
Functions group commands under a name. They take arguments like a script, but run inside the current shell. The bash(1) manual page describes their behaviour:
- Functions run in the current shell, not in a subshell.
- While a function runs, its arguments replace the positional parameters ($1, $2, …), and
FUNCNAMEholds its name. localcreates variables with dynamic scope.returnsets the function's exit status. Without it, the status is that of the last command.
Syntax
| Form | Notes |
|---|---|
name() { commands; } | POSIX form, works in sh too |
function name { commands; } | Bash form |
name() ( commands ) | Body in a subshell: changes to variables or cd don't leak out |
Good practice
| Practice | Why |
|---|---|
local for all internal variables | No accidental changes to global variables |
| Return status codes, print data to stdout | Callers can use if fn; then and $(fn) |
| Messages to stderr | They don't end up in captured output |
| Check arguments at the start | Clear errors instead of strange behaviour |
export -f name only when needed | Makes the function available to child Bash processes |
A small utility library
host$ cat ~/.bash_functions
die() { printf 'error: %s\n' "$*" >&2; return 1; }
port_open() {
local host=${1:?host} port=${2:?port}
timeout 2 bash -c ">/dev/tcp/$host/$port" 2>/dev/null
}
svc_restart() {
local unit=${1:?unit}
sudo systemctl restart "$unit" || return
systemctl is-active --quiet "$unit" || die "$unit did not come up"
}
host$ source ~/.bash_functions
host$ port_open 10.30.0.11 22 && echo open || echo closed
open
host$ svc_restart nginx; echo "status=$?"
status=0
host$ declare -f port_open | head -3
host$ type svc_restart | head -1
svc_restart is a function
Reading the example
${1:?host} stops the function with a clear message when an argument is missing. || return passes the exit status of a failed restart on to the caller. Both are short ways to make functions fail loudly and predictably.
Documented example, not captured output.
How it works at runtime
Functions is part of Shell & Bash → Functions. Bash Functions are named shell command groups executed in the current shell context by default, with positional parameters and access to shell variables, options, traps and descriptors.
Topic-specific state model. Bash Functions are named shell command groups executed in the current shell context by default, with positional parameters and access to shell variables, options, traps and descriptors.
Interpretation rule. - Function call ≠ new process; current-shell state can be changed.
- return status ≠ output value; stdout is data while return accepts shell status range.
- local variable ≠ lexical scope in the general programming-language sense; Bash uses dynamic scoping behavior.
- Exported function ≠ portable or universally safe process interface.
Quick reference
Bash functions group commands and accept arguments:
log() { printf '%s %s\n' "$(date +%FT%T)" "$*" >&2; }
backup_file() {
local f=$1
[[ -f $f ]] || { log "missing $f"; return 1; }
cp -a -- "$f" "$f.$(date +%Y%m%d%H%M)"
}
backup_file /etc/nginx/nginx.conf || exit 1
declare -f backup_file # show definition
Use local for variables inside functions, return status codes (0 success) rather than echoing "true", and send logs to stderr so callers can capture stdout as data.
Limits and how it fails
Primary failure point. Function verification shows behavior in the current Bash state and tested arguments; it does not imply subprocess isolation or portability to other shells.
ReferenceConfiguration & state1 section · depth on demand
Configuration, persistence and lifecycle
Distribution/platform context. Variables owns binding/export semantics; Shell Scripts owns executable script boundaries; this Topic owns reusable in-shell functions.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Shell & Bash → Functions. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://www.gnu.org/software/bash/manual/bash.html · confidence 94%What changed and what may be affected
Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.
Terms & aliases
Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.
Quick lookup tables
Functions operational reference
Topic-specific lookup boundaries, proof limits and next-step Evidence for Functions.
| Lookup boundary | Topic-specific reference | Operational use |
|---|---|---|
| Scope / effective state | Bash Functions are named shell command groups executed in the current shell context by default, with positional parameters and access to shell variables, options, traps and descriptors. | Establish exactly what this Topic owns before crossing into another subsystem. |
| Fast verification | Pin host/distribution + shell/version/mode → identify cwd/mount namespace + input/path/stream → preserve quoting/expansion and final argv → map fd/pipeline/process boundaries → inspect object/variable/status/signal state → make one minimal reversible change → read back effective state → repeat original consumer/script/workload test. | Use the shortest evidence path first; a fast check is a boundary test, not blanket proof. |
| Verification chain | function definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behavior | Trace requested/configured state through effective state to the observed workload result. |
| Failure boundary | Function verification proves behavior in the current Bash state and tested arguments; it does not imply subprocess isolation or portability to other shells. | Stop broad troubleshooting at the first boundary that is not supported by evidence. |
| Positive evidence | Correlated Linux file/text/shell evidence can establish this proof path: function definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behavior | Use this observation only for the specific claim it actually supports. |
| Evidence limit | It does not independently prove behavior outside the captured host, shell/session, cwd/namespace, input, process, filesystem, locale, time or workload scope. Function verification proves behavior in the current Bash state and tested arguments; it does not imply subprocess isolation or portability to other shells. | Do not promote a local success signal into end-to-end or adjacent-dependency proof. |
| Next troubleshooting check | Continue from the first unproven boundary: capture the exact shell-delivered argv/streams or resolved object, verify the effective target state, change only the demonstrated cause, then repeat the original consumer/script/workload and adjacent regression checks. | Continue to the next unresolved boundary while preserving the original test condition. |
Functions · operational reference
Compact Linux state, persistence, verification and boundary reference for fast lookup.
| Reference boundary | Functions |
|---|---|
| Topic path | Shell & Bash → Functions |
| Runtime state | Bash Functions are named shell command groups executed in the current shell context by default, with positional parameters and access to shell variables, options, traps and descriptors. |
| Fast checks | - Inspect function definition with the shell's own introspection and confirm which definition wins command resolution. - Test positional parameters, empty arguments, local/global variable interactions and return statuses. - Identify intentional current-shell side effects such as cwd/options/traps/environment. - Verify callers handle both stdout and return status correctly and that external subprocess boundaries are explicit. |
| Verification chain | function definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behavior Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return/regression → explicit Evidence boundary. Boundary chain: local authoritative state → adjacent dependency → effective/programmed state → original workload/request → return path or regression → explicit Evidence boundary. |
| Failure boundary | Function verification proves behavior in the current Bash state and tested arguments; it does not imply subprocess isolation or portability to other shells. Boundary chain: process/context → userspace configuration → kernel subsystem/resource → device/network/filesystem dependency → effective state → original workload. |
| Persistence rule | Prove which configuration source owns the state, then prove that the running consumer loaded or generated the intended state. |