Terminal · intermediate

Shell functions

A shell function is a named compound command that runs in the current shell environment with its own positional parameters and returns a shell exit status.

Why it matters

Functions remove repetition and can deliberately update shell state, but their stdout, status, and variable scope form an interface that callers must understand.

Mental model

How to reason about shell functions

Calling a function temporarily replaces positional parameters, executes its body in the current shell, restores the caller's parameters, and exposes output and a final status.

Analogy

A function is a reusable workstation inside the same workshop: it gets a fresh input tray but can still alter shared tools unless its variables are made local where supported.

Examples

See the boundary, not just the happy path

Worked example · Return data through stdout

slugify() { printf '%s' "$1" | tr '[:upper:] ' '[:lower:]-'; }

The function accepts its value as $1 and emits transformed data on stdout, allowing callers to capture or pipe the result.

Worked example · Return success or failure

is_readable() { [ -f "$1" ] && [ -r "$1" ]; }

The function's status is the status of its final command list, so it can be used directly as an if condition without printing true or false.

Useful contrast · return is not stdout

value() { return 42; }

Shell return supplies a numeric status rather than arbitrary result data; use stdout for text values and reserve status for outcome.

Common mistakes

Misconceptions to remove early

Using global scratch variables accidentally

Functions share shell variables by default; Bash local declarations or disciplined names prevent temporary state from overwriting caller state.

Mixing diagnostics with returned data

If a caller captures stdout, debug messages become part of the value; send diagnostics to stderr.

Quick check

Can you predict the result?

1. How should a shell function normally communicate arbitrary text data to a command-substitution caller?
  • Write the data to standard output.
  • Use return with the text.
  • Change the process exit signal.
Answer: Write the data to standard output.
2. Does an ordinary shell function run in a separate process by definition?
Answer: No; it normally runs in the current shell environment unless placed in a subshell or pipeline context that creates one.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster