Bash Functions
A function gives a name to a group of commands so you can run them many times, with different arguments. Functions make scripts shorter, readable and testable, and they behave like small commands of their own: they take arguments, write output and return an exit status.
Defining and calling
greet() {
echo "Hello, $1!"
}
greet Ada
greet "Grace Hopper"Hello, Ada!
Hello, Grace Hopper!
Define a function before you call it. The alternative syntax function greet { ... } also works in Bash, but name() { ... } is the portable form. You call a function exactly like a command: name, then arguments, no parentheses.
Arguments
Inside a function, $1, $2 … are the function's own arguments, $# is their count and "$@" is all of them:
describe() {
echo "called with $# argument(s)"
echo "first: ${1:-<none>}, second: ${2:-<none>}"
for arg in "$@"; do echo " - $arg"; done
}
describe
describe red "light blue"called with 0 argument(s)
first: <none>, second: <none>
called with 2 argument(s)
first: red, second: light blue
- red
- light blue
Returning values
Bash functions don't return values like other languages. There are two channels:
| Channel | How | Use for |
|---|---|---|
| Exit status | return N (0–255), read with $? or if |
Success/failure, yes/no |
| Output | echo/printf, captured with $(...) |
Data: strings, numbers, lists |
is_even() {
(( $1 % 2 == 0 ))
}
square() {
echo $(( $1 * $1 ))
}
for n in 3 4; do
if is_even "$n"; then echo "$n is even"; else echo "$n is odd"; fi
done
result=$(square 12)
echo "12 squared is $result"3 is odd
4 is even
12 squared is 144
is_even doesn't even need return: a function's exit status is that of its last command. Functions that answer yes/no read naturally in if.
find_user() {
local name=$1
if grep -q "^$name:" /etc/passwd; then
return 0
fi
echo "no such user: $name" >&2
return 1
}
find_user learner && echo "learner exists"
find_user gandalf || echo "status was $?"learner exists
no such user: gandalf
status was 1
Error messages go to standard error (>&2), so they don't end up in a variable when someone captures the function's output.
Local variables
Variables in Bash are global by default, even inside functions. Declare function-internal variables with local so they don't overwrite anything outside:
count=100
leaky() { count=1; }
careful() { local count=2; echo "inside careful: $count"; }
careful
echo "after careful: $count"
leaky
echo "after leaky: $count"inside careful: 2
after careful: 100
after leaky: 1
Tip: Make
locala habit for every variable in a function. Bugs caused by a function silently changing a global variable namediorfileare very hard to find.
Practical helpers
Real scripts start with a few small utility functions. A logger and a "die" function are the classics:
log() { printf '[%s] %s\n' "$1" "${*:2}"; }
die() { log ERROR "$*"; exit 1; }
require_file() { [ -f "$1" ] || die "missing file: $1"; }
touch settings.conf
log INFO "starting"
require_file settings.conf
log INFO "settings found"
require_file secrets.conf
log INFO "this line is never reached"[INFO] starting
[INFO] settings found
[ERROR] missing file: secrets.conf
${*:2} means "all arguments from the second one on", joined by spaces. exit inside a function ends the whole script, which is exactly what die is for.
Recursion and arrays
Functions can call themselves. Arrays are passed as separate arguments ("${arr[@]}") and received with "$@":
factorial() {
local n=$1
if (( n <= 1 )); then echo 1; return; fi
echo $(( n * $(factorial $(( n - 1 ))) ))
}
sum() {
local total=0 x
for x in "$@"; do (( total += x )); done
echo "$total"
}
echo "5! = $(factorial 5)"
prices=(12 30 8)
echo "sum = $(sum "${prices[@]}")"5! = 120
sum = 50
Listing and removing functions
declare -F lists defined function names, declare -f name prints a function's source, type name says it's a function and unset -f name deletes it.
backup() { echo "backing up $1"; }
type backup | head -n 1
declare -F | grep backup
unset -f backup
backup notes.txtbackup is a function
declare -f backup
/w/main.sh: line 5: backup: command not found
Test yourself
How do you call the function deploy with the argument prod?
- deploy(prod)
- deploy prod
- call deploy prod
- $deploy prod
How does a function hand back a string to the caller?
- return "text"
- It prints it, and the caller captures it with $(...)
- It sets $?
- With export
What does local do?
- Makes a variable read-only
- Limits a variable to the function (and functions it calls)
- Exports a variable
- Makes a variable an integer