The Analogy: The Short-Order Kitchen's Prep Station
Stand at the pass of a busy short-order kitchen and watch a single prep station work. An order ticket comes in -- "two eggs, over easy, side of toast" -- and the cook at that station follows the same fixed routine every time, whatever the ticket says: read the ticket, pull the ingredients named on it, cook to the standard method, plate, and push the plate out to the pass. The station is a reusable procedure. It does not care which ticket arrives; it takes the details from the ticket and produces a dish. A shell function is exactly this station: a named block of commands that you can call over and over, and each call hands it a fresh ticket -- the arguments.
The ingredients on the ticket arrive in order, and the cook refers to them by position: the first item, the second item, the third. A shell function does the same with $1, $2, $3, and it can see the whole ticket at once as $@ and count the items with $#. The cook does not keep a private note of "the customer's name" scrawled on the shared whiteboard where it would confuse the next station; a careful cook uses their own scratch pad for working notes. That private scratch pad is local: a variable declared local inside a function exists only for that call and does not disturb variables of the same name elsewhere in the script.
Now the crucial distinction, the one that trips up everyone new to the kitchen. When the dish is ready, two entirely separate things happen. The cook rings the little bell at the pass, and the cook puts the plate on the pass shelf. The bell is a signal -- ready, or one short ring for "I burned it, remake". The plate is the actual food. In a shell function, ringing the bell is return, which carries only a small status number from 0 to 255; putting the plate out is echo (or any write to standard output), and the way a caller collects that plate is command substitution, result=$(station ...). The bell tells you whether it went well; the plate is what you actually eat.
The failure mode is confusing the bell for the plate. A runner who listens for the bell and then tries to serve the customer "a table with the number three on it" -- because the bell rang three times -- has misunderstood the whole system, and the customer goes hungry. In the shell this is the person who writes return $total expecting to read the total back as a value, then discovers two nasty surprises: the number was silently wrapped into the 0-to-255 range (so a total of 300 comes back as 44), and it was never a value to be captured anyway, only a status to be inspected with $?. And the cook who scribbles on the shared whiteboard instead of a scratch pad -- a function that omits local -- quietly overwrites a variable the rest of the script was relying on, a bug that surfaces far from the function that caused it.
Syntax or Core Structure
A function is declared with a name followed by () and a brace-delimited body. It is called by writing its name as if it were a command, with arguments after it -- no commas, no parentheses at the call site. Inside, $1, $2, and so on name the arguments by position. This function greets a name a given number of times.
#!/usr/bin/env bash
greet() {
local name=$1
local times=$2
local i
for (( i = 1; i <= times; i++ )); do
echo "Hello, $name (#$i)"
done
}
greet World 2
greet Bash 1
Output:
Hello, World (#1)
Hello, World (#2)
Hello, Bash (#1)
The function is defined once and called twice. The first call, greet World 2, sets name to World and times to 2, so the loop runs twice. The second call, greet Bash 1, reuses the identical body with new arguments and runs once. Note three things that matter throughout this lesson: the arguments are given positionally with plain spaces, not a comma-separated list; each parameter is copied into a local variable at the top so the function does not depend on or disturb anything outside it; and the function must be defined before it is called, because the shell reads a script top to bottom and cannot call a name it has not yet seen.
Technical Depth: Status Versus Value, Scope, and Recursion
The bell and the plate: return versus echo
This is the single most important idea about shell functions. return sets the exit status, an integer from 0 to 255, retrieved by the caller as $?. It does not hand back a value. To produce a value, the function writes it to standard output with echo or printf, and the caller captures it with command substitution. The table lays out the four ways data crosses a function boundary.
| Mechanism | Carries | Range or type | Retrieved with |
|---|---|---|---|
| return N | exit status | integer 0 to 255 | the $? variable |
| echo value | text on stdout | any string | command substitution |
| global var | shared state | any string | reading it directly |
| local var | function-only state | any string | not visible outside |
#!/usr/bin/env bash
add_status() { return $(( $1 + $2 )); }
add_value() { echo $(( $1 + $2 )); }
add_status 3 4
echo "status form: exit code is $?"
sum=$(add_value 3 4)
echo "value form: captured $sum"
big() { return 300; }
big
echo "return 300 wraps to $?"
Output:
status form: exit code is 7
value form: captured 7
return 300 wraps to 44
Both forms compute 7, but they deliver it differently. add_status uses return, so the 7 arrives as an exit status read through $?. add_value uses echo, so the 7 arrives as text captured into sum. The third call proves why return is the wrong channel for real values: return 300 wraps modulo 256 and comes back as 44, because exit statuses are a single byte. Whenever a function needs to hand back a number larger than 255, a string, or anything that is not strictly a pass or fail signal, it must echo the value and be captured, never return it.
Scope: the scratch pad versus the whiteboard
By default a variable assigned inside a function is global -- it modifies the surrounding script. The local keyword confines a variable to the function call. Getting this wrong is a classic source of action-at-a-distance bugs.
#!/usr/bin/env bash
counter=100
leaky() { counter=1; echo " inside leaky, counter=$counter"; }
safe() { local counter=1; echo " inside safe, counter=$counter"; }
echo "before: counter=$counter"
safe
echo "after safe: counter=$counter"
leaky
echo "after leaky: counter=$counter"
Output:
before: counter=100
inside safe, counter=1
after safe: counter=100
inside leaky, counter=1
after leaky: counter=1
safe declares local counter, so its assignment shadows the global for the duration of the call and the global is untouched afterward -- it is still 100. leaky assigns counter without local, so it reaches out and clobbers the global, which reads 1 after the call. In a large script the leaky pattern is insidious: the function looks self-contained, but it silently corrupts a variable some distant loop was using. Declaring every function-internal variable local is close to mandatory discipline.
Recursion with captured output
Because a function can call itself and hand values back through echo and capture, recursion works cleanly. This factorial captures the result of the smaller sub-problem and multiplies.
#!/usr/bin/env bash
fact() {
local n=$1
if (( n <= 1 )); then echo 1; return; fi
local prev
prev=$(fact $(( n - 1 )))
echo $(( n * prev ))
}
for k in 1 3 5; do
echo "fact($k) = $(fact $k)"
done
Output:
fact(1) = 1
fact(3) = 6
fact(5) = 120
Each call declares its own local n and local prev, which is what makes recursion safe: without local, every level would share one n and the recursion would corrupt itself. The base case echoes 1 and returns; the recursive case captures the previous factorial with prev=$(fact ...) and echoes the product. The bare return after the base-case echo carries no number -- it simply ends the function early, having already put its plate (the 1) on the pass. Recursion in Bash is correct but slow, because each level spawns a command-substitution subshell; for anything hot, an iterative loop is far cheaper.
Real World Example: A Sales Report From Reusable Functions
A report generator is a natural home for functions: one to compute a derived value, one to format a field, and one to drive the whole thing. This program reads region sales as "region units price", computes revenue per region, tracks the total and the top region, and prints an aligned table. Every piece of arithmetic and formatting is a small reusable function.
#!/usr/bin/env bash
set -u
revenue() { echo $(( $1 * $2 )); }
pad() { printf '%-*s' "$2" "$1"; }
report() {
local region units price rev total=0 top_region="" top_rev=0
while read -r region units price; do
rev=$(revenue "$units" "$price")
total=$(( total + rev ))
if (( rev > top_rev )); then
top_rev=$rev
top_region=$region
fi
printf '%s units=%2d rev=%4d\n' "$(pad "$region" 6)" "$units" "$rev"
done
echo "-----------------------------"
printf 'total revenue: %d\n' "$total"
printf 'top region: %s (%d)\n' "$top_region" "$top_rev"
}
report <<'DATA'
north 10 25
south 4 25
east 7 30
west 12 20
DATA
Output:
north units=10 rev= 250
south units= 4 rev= 100
east units= 7 rev= 210
west units=12 rev= 240
-----------------------------
total revenue: 800
top region: north (250)
Trace the composition. For each line, report calls revenue with the units and price and captures the product: north is 10 times 25, or 250; south is 4 times 25, or 100; east is 7 times 30, or 210; west is 12 times 20, or 240. Those sum to 800, printed as the total. The pad function is called inside the printf argument list with command substitution so the region name is left-justified to six columns and the table aligns. Notice how revenue and pad are pure and reusable: they take inputs, echo a result, and touch no shared state, which is exactly what makes them safe to call from inside a loop.
The top-region logic and the parsing hide three genuine defects worth naming. First, the tie-break is silent and order-dependent: the test rev > top_rev is strictly greater-than, so if two regions had equal revenue the first one seen would keep the title and the later one would be ignored without any note -- fine if you know the data has no ties, dangerous if you do not. Second, the money is integer-only: a realistic price like 24.99 cannot be represented, and revenue would be silently wrong, so a real tool would use scaled-integer cents or a decimal calculator. Third, report does no validation of field count; a line with only two fields leaves price empty, and revenue then evaluates $(( units * )), which is an arithmetic syntax error that aborts the line -- a robust version would check that read populated all three fields before using them.
Common Mistakes
- Using return to hand back a value.
return $totaldoes not return the total; it sets the exit status, which is capped at 0 to 255 and wraps beyond that. A total of 300 comes back as 44. To return a value,echoit and capture the function with command substitution.
- Calling a function with parentheses or commas.
myfunc(a, b)is not a function call in Bash; it is a syntax error or a subshell. Functions are called like commands:myfunc a b, with space-separated arguments and no parentheses at the call site.
- Omitting local and clobbering a caller variable. A plain assignment inside a function is global. A function that sets
iorcountwithoutlocalsilently overwrites the caller's variable of the same name, producing bugs that appear far from the function. Declare every internal variablelocal.
- Defining a function after the call that uses it. The shell reads top to bottom, so a call placed above the function's definition fails with "command not found". Define functions before the code that calls them, or gather all definitions near the top of the script.
- Letting a function's stray output pollute a captured value. When you capture
x=$(func), every byte the function writes to stdout becomes part ofx, including debugecholines. Send diagnostics to standard error with>&2so they do not contaminate the captured value.
- Forgetting that positional parameters shift inside a function. Inside a function,
$1is the function's first argument, not the script's. If you need the script's arguments, capture them before entering the function;$@inside the function refers only to what that function was called with.
- Assuming a variable set in a piped function survives. A function on the right of a pipe runs in a subshell, so any global it sets is lost when the pipe ends -- the same subshell trap that affects loops. Capture the function's output instead, or avoid the pipe.
- Relying on recursion for deep or hot work. Each recursive call that captures output spawns a subshell, so deep recursion is slow and can exhaust resources. Bash has no tail-call optimization; convert hot recursion to an explicit loop.
- Naming a function after an existing command. Defining a function called
test,cd, orlsshadows the builtin or program for the rest of the script, and later code that expected the real command misbehaves. Use distinct, descriptive function names to avoid masking commands.
Best Practices
- Return status, echo values. Use
returnonly for a pass or fail signal in the 0-to-255 range, andecho(captured with command substitution) for any actual data. Keeping the two channels separate is the core discipline of writing Bash functions.
- Declare every internal variable local. Put
localon each variable a function assigns, including loop counters. This prevents the function from reaching out and corrupting the caller's state and makes the function safe to call from anywhere, including from within loops.
- Send diagnostics to standard error. Route progress messages, warnings, and debug output to
>&2so they appear on the terminal but never end up inside a captured value. Reserve standard output for the function's real result.
- Define functions before you call them. Place definitions near the top of the script, above the driving logic. This respects the shell's top-to-bottom reading and keeps the reusable pieces gathered in one readable block.
- Keep functions pure where you can. A function that takes its inputs as arguments and produces its output on stdout, touching no globals, is easy to test, reuse, and reason about. Reserve global-mutating functions for genuine shared state and name them clearly.
- Validate arguments at the top of the function. Check
$#or test that required parameters are non-empty before using them, and fail with a clear message on stderr. A function that assumes well-formed input produces confusing errors deep in its body when the assumption breaks.
- Prefer iteration to recursion for anything hot. Bash recursion is correct but pays a subshell per level. When a problem can be expressed as a loop with an accumulator, the loop is dramatically faster and uses constant depth.
- Give functions descriptive, non-colliding names. Avoid names that shadow builtins or common commands. A name like
compute_revenuedocuments intent and cannot accidentally masktestorprintffor the rest of the script.
Practice Exercises
- Value versus status. Write two functions that both compute the maximum of two numbers: one that
echos the result and one that tries toreturnit. Call each, capture or inspect the result, and demonstrate with an input above 255 that thereturnversion wraps while theechoversion is correct. Explain the wrap in a comment.
- A scope experiment. Write a function that increments a counter, first without
localand then with it, and show from the caller how the global counter is affected in each case. Add a second function that calls the first inside a pipe and show that the global change is lost, explaining why.
- A small formatting library. Write three reusable functions -- one that pads a string to a width, one that formats an integer with a fixed field, and one that draws a separator line of a given length -- and use them together to print an aligned two-column table from a here-document. Keep all three functions pure.
- Guarded recursion. Write a recursive function that computes a sum from 1 to N, but add argument validation that rejects a negative or non-numeric N with a message on stderr and a non-zero status. Show it producing the right sum for a valid input and a clear error for an invalid one, and explain why the validation belongs at the top of the function.