On this page
- How do I define and call a function?
- How are arguments passed into a function?
- How do I return a value from a function?
- Why should variables in functions be local?
- How can a function fill a variable or array for the caller?
- How do I share functions between several scripts?
- What does a well structured script with functions look like?
- How do I inspect or debug a function?
- Questions
How do I define and call a function?
Write a name, a pair of parentheses and a body in braces, then call the name later in the script, after the definition:
#!/usr/bin/env bash
say() {
printf '[%s] %s\n' "$(date +%T)" "$*"
}
say "starting maintenance"
say "done"Bash reads a script top to bottom, so a call placed before the definition fails with command not found. The keyword form function say { ... } also works, but the parentheses form is portable and more common. The body needs a space after { and either a newline or a semicolon before }. Within a function, $* joins all arguments into one string and "$@" keeps them separate, the same as in a script.
How are arguments passed into a function?
Exactly like arguments to a script: the caller lists them after the name, and inside they appear as positional parameters. The script's own arguments are hidden while the function runs:
make_site_dir() {
local domain="$1" owner="${2:-deploy}"
if (( $# < 1 )); then
echo "make_site_dir: domain required" >&2
return 2
fi
sudo install -d -o "$owner" -g "$owner" -m 755 "/var/www/$domain"
echo "/var/www/$domain"
}
make_site_dir app.example.net
make_site_dir shop.example.net www-dataCopying $1 into a named local variable at the top makes the body readable and documents what the function expects. $# is the argument count for the function, and shift drops the first argument, which helps when you parse options inside a function. On Rocky and Alma the web server user is nginx or apache instead of www-data.
How do I return a value from a function?
Use the exit status for success or failure and standard output for data. return only accepts a number between 0 and 255, so it cannot carry text:
is_port_open() {
ss -ltnH "sport = :$1" | grep -q .
}
free_port() {
local p
for (( p = ${1:-8000}; p < 9000; p++ )); do
is_port_open "$p" || { echo "$p"; return 0; }
done
return 1
}
if is_port_open 22; then echo "SSH is listening"; fi
port=$(free_port 8080) || { echo "no free port" >&2; exit 1; }
echo "using $port"Without an explicit return, a function returns the status of its last command, which is why is_port_open needs only one line. Keep anything that is not the result, such as progress messages, on standard error (>&2) so it does not end up inside the captured value.
Why should variables in functions be local?
Variables in Bash are global by default, so a function that sets i or file silently changes the caller's variable of the same name. Declare them with local to scope them to the function and anything it calls:
file="report.txt"
tidy() {
local file
for file in /tmp/myapp-*; do rm -f -- "$file"; done
}
tidy
echo "$file" # still report.txtWithout the local line, the last echo would print a temp file path. One subtle trap: local out=$(cmd) always returns status 0 because local itself succeeds, hiding a failure of cmd. Split it into local out and out=$(cmd) on separate lines when you check the result. The same applies to export and readonly.
How can a function fill a variable or array for the caller?
Capture output with $( ) for simple strings; for arrays or several values, pass the name of the target variable and use a nameref (local -n, Bash 4.3 and later):
list_users() {
local -n _out="$1"
mapfile -t _out < <(awk -F: '$3 >= 1000 && $3 < 60000 {print $1}' /etc/passwd)
}
list_users people
echo "${#people[@]} users: ${people[*]}"The nameref _out becomes an alias for people, so writing to it fills the caller's array without a subshell. Give the nameref an unusual name like _out, because a nameref that matches the caller's variable name refers to itself and fails. This pattern avoids the cost and the lost variables of command substitution. Array basics are in Arrays in Bash.
How do I share functions between several scripts?
Put them in a library file and load it with source (or its short form .). The library has no shebang and needs no execute bit:
sudo install -d /usr/local/lib/ops
sudo tee /usr/local/lib/ops/common.sh >/dev/null <<'EOF'
log() { printf '%s %s\n' "$(date -Is)" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
need() { command -v "$1" >/dev/null || die "missing command: $1"; }
EOF#!/usr/bin/env bash
source /usr/local/lib/ops/common.sh
need rsync
log "sync started"A die helper that logs and exits keeps error paths to one line throughout your scripts. To find a library next to the script regardless of the working directory, use source "$(dirname "$(readlink -f "$0")")/common.sh". The heredoc used above is explained in Heredocs and writing to files.
What does a well structured script with functions look like?
A tidy layout puts settings first, functions next and a main function last, called with all arguments at the very bottom:
#!/usr/bin/env bash
set -euo pipefail
readonly DEST="/srv/archive"
usage() { echo "usage: ${0##*/} DIR..." >&2; exit 2; }
pack() {
local src="$1" out
out="$DEST/$(basename "$src")-$(date +%F).tar.gz"
tar -czf "$out" -C "$(dirname "$src")" "$(basename "$src")"
echo "$out"
}
main() {
(( $# )) || usage
mkdir -p "$DEST"
local d
for d in "$@"; do pack "$d"; done
}
main "$@"Because nothing runs until the last line, the whole file is parsed before work starts, and a half uploaded script cannot execute half its steps. The set -euo pipefail line is explained in Error handling with set -euo pipefail and trap.
How do I inspect or debug a function?
List a function's current definition with declare -f name or type name, and trace a single call by wrapping it in set -x and set +x:
declare -f pack
type say
set -x; pack /srv/app; set +x # trace one call only
declare -F # names of all defined functions
unset -f say # remove a functionThe FUNCNAME array holds the call stack and BASH_LINENO the line numbers, useful in a die helper that reports where the error happened: echo "failed in ${FUNCNAME[1]} at line ${BASH_LINENO[0]}". Functions defined in ~/.bashrc are available in every interactive shell, which is handy for small personal helpers described in Aliases and a tidy .bashrc.
Questions about Functions in Bash
Can a function have the same name as a command?
Yes, and the function wins. Inside it, call the real program with command ls to avoid endless recursion.
Why does return 300 give a different number?
Exit codes are 8 bits, so values wrap modulo 256 and 300 becomes 44. Print larger numbers to standard output instead.
Can a function call itself?
Yes, recursion works, but every call costs time and Bash has no tail call optimisation. A loop is usually simpler.
Do functions see the script's variables?
Yes, global variables are visible and writable unless shadowed by a local declaration. Pass values as arguments anyway; it keeps functions testable.
How do I make a function available to child scripts?
Run export -f name. The child must also be Bash. For tools like xargs or find -exec, call bash -c 'name "$@"' _ args.