Pcornel
Browse topics
Options
Recent
Favorites
Linux · Technical reference

Functions

Direct answer

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.

When to use this

Use it to reuse logic in scripts and shells, or when a function's result or exit code is wrong.

First 30 seconds

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.

Operational verification

function defined → called with arguments → runs in the current shell → output written, status returned

Evidence · next step

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
Platform / version applicability
linux
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

Platformlinux
Scope / prerequisiteUse it to reuse logic in scripts and shells, or when a function's result or exit code is wrong.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

5 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 local for function variables.
Evidence references

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.

observation · 1
Key points

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.

Key checks
  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — 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 FUNCNAME holds its name.
  • local creates variables with dynamic scope.
  • return sets the function's exit status. Without it, the status is that of the last command.

Syntax

FormNotes
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

PracticeWhy
local for all internal variablesNo accidental changes to global variables
Return status codes, print data to stdoutCallers can use if fn; then and $(fn)
Messages to stderrThey don't end up in captured output
Check arguments at the startClear errors instead of strange behaviour
export -f name only when neededMakes 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor doclinux current

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%
Technical changelog & impact

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.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

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.

Aliases that resolve here
bash functionsshell function linuxbash local variablesbash return status
Embedded reference data

Quick lookup tables

Functions operational reference

Topic-specific lookup boundaries, proof limits and next-step Evidence for Functions.

Lookup boundaryTopic-specific referenceOperational use
Scope / effective stateBash 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 verificationPin 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 chainfunction definition → command resolution → caller shell + positional parameters → local/dynamic variable scope → builtins/external commands → return status + shell-state side effects → caller behaviorTrace requested/configured state through effective state to the observed workload result.
Failure boundaryFunction 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 evidenceCorrelated 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 behaviorUse this observation only for the specific claim it actually supports.
Evidence limitIt 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 checkContinue 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 boundaryFunctions
Topic pathShell & Bash → Functions
Runtime stateBash 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 chainfunction 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 boundaryFunction 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 ruleProve which configuration source owns the state, then prove that the running consumer loaded or generated the intended state.
Confirmation

Confirm action

Continue?