Functions & Arguments
Structure scripts with reusable functions, parameters, and return values.
Theory
Functions group related logic so scripts stay readable and DRY. Inside a function,
arguments are $1, $2, $@ — just like a script. A function communicates back
in two ways:
- Exit status via
return N(0–255) — for success/failure - Output via
echocaptured withresult=$(myfunc)— for actual data
Use local to scope variables inside a function so they don’t leak into the
global namespace and cause spooky bugs.
Real-World Example
#!/usr/bin/env bash
log() { # a helper used everywhere
local level="$1"; shift
echo "[$level] $*"
}
add() {
local sum=$(( $1 + $2 ))
echo "$sum" # output, captured by caller
}
is_even() {
(( $1 % 2 == 0 )) && return 0 || return 1
}
log INFO "starting"
total=$(add 3 4) # total = 7
if is_even "$total"; then log INFO "even"; else log INFO "odd"; fi Hands-On Exercise
- Write a
greetfunction that takes a name and prints a greeting. - Write a function that returns success/failure based on whether a file exists.
- Use
localto prove a variable doesn’t leak outside the function. - Capture a function’s echoed result into a variable and use it.
Cheat Sheet▾
| Item | Syntax |
|---|---|
| Define | name() { … } |
| Arguments | $1 $2 $@ $* |
| Local variable | local x=… |
| Return status | return N (0–255) |
| Shift args | shift |
| Capture output | r=$(func args) |
Common Interview Questions▾
How does a Bash function return a value?
Two channels: return sets an exit status (0–255) for success/failure, while
data is returned by echoing it and capturing with $(func).
Why use local in functions?
It scopes a variable to the function so it doesn’t overwrite or leak into global variables — preventing subtle bugs in larger scripts.
Official Documentation
📝 My notes on this topic
Auto-saves as you type