← Full reference

Bash functions

Declaring functions, arguments $1 $@ $#, local, return and returning output, source and export -f

A bash function is a named piece of code that you call like a regular command: name arg1 arg2. Functions remove repetition from scripts, and when moved to a separate file and loaded with source, they become a library. A function has no declared parameters or return value in the usual sense: arguments arrive in $1, $2, …, and what it gives back is its exit code and whatever it printed to stdout.

Syntax

name() {                 # main form (POSIX)
    commands
}

function name {          # bash form; function name() { … } works too
    commands
}

name() ( commands )       # a body in parentheses runs in a subshell

name arg1 "arg 2"        # call

A function must be declared before its first call. The one-line form needs ; before }: hi() { echo hi; }.

Arguments inside a function

NotationWhat it is
$1 … $9, ${10}the function's positional arguments (from the tenth on — only in braces)
$#number of arguments
"$@"all arguments, each as a separate word, preserving inner spaces
"$*"all arguments as one string joined by the first character of $IFS (a space)
${@: -1}last argument
shift / shift Nshift the arguments: $2 becomes $1 and so on
$0name of the script (or bash), not of the function
${FUNCNAME[0]}name of the current function; ${FUNCNAME[1]} — of its caller

The script's arguments aren't visible inside a function: $1 in a function is the function's first argument. To pass the script's arguments, call f "$@".

Variables: global and local

NotationWhat it does
x=1without a declaration the variable is global: visible and modifiable across the whole script
local x=1the variable is visible only in this function and in the functions it calls
local -a arr / local -A map / local -i nlocal array / associative array / integer
declare x=1 (inside a function)same as local
declare -g x=1an explicitly global variable from inside a function

How to return a result

MethodExampleWhen
exit codereturn 0 / return 1"yes/no", "success/failure"; a number 0–255
print to stdoutecho "$res", then x=$(f)return a string or a number
global variableRESULT=…no subshell, but the function and the caller are coupled
variable referencelocal -n out=$1; out=…write the result into a variable whose name is passed as an argument

Without return, a function returns the exit code of the last command it ran.

Managing functions

CommandWhat it does
declare -Flist names of declared functions
declare -f name / type nameshow a function's body
unset -f namedelete a function
export -f namepass a function to child bash processes
source file / . filerun a file in the current shell: its functions and variables stay available

Examples

# a simple function with arguments and a default value
greet() {
    local name=${1:-world}
    echo "Hello, $name!"
}
greet            # Hello, world!
greet Anna       # Hello, Anna!

# a check function: the result is the exit code
is_number() {
    [[ $1 =~ ^[0-9]+$ ]]
}
if is_number 42; then echo "number"; fi

# a function returns a string via stdout
to_upper() {
    echo "${1^^}"
}
name=$(to_upper "hello")      # HELLO

# error message goes to stderr so it doesn't end up in $(…)
die() {
    echo "error: $*" >&2
    exit 1
}
[[ -f /etc/hosts ]] || die "no /etc/hosts"

# iterate over all arguments, preserving spaces
show_args() {
    echo "arguments: $#"
    for a in "$@"; do echo "<$a>"; done
}
show_args "one two" three

# return a value into a variable by name (nameref)
get_size() {
    local -n _out=$1
    _out=$(wc -c < "$2")
}
get_size bytes /etc/hostname
echo "$bytes"

# a function library in a separate file
cat > /tmp/lib.sh <<'EOF'
log() { echo "[$(date +%T)] $*"; }
EOF
source /tmp/lib.sh
log "starting"

# a function available to a child bash (e.g. in xargs or find -exec)
check() { echo "checking $1"; }
export -f check
printf '%s\n' a b | xargs -I{} bash -c 'check "$1"' _ {}

Pitfalls

  • Variables are global by default. Assigning i=… inside a function overwrites i in an outer loop. Declare working variables with local.
  • return is only a code 0–255. return 300 returns 44 (the remainder of division by 256). Return strings and large numbers via echo and $(…).
  • Everything a function prints ends up in $(f). Write debug and diagnostic messages to stderr: echo "…" >&2.
  • $(f) runs the function in a subshell. Variable changes and cd inside it don't leak out.
  • local x=$(cmd) loses the exit code of cmd. $? after such a line is the code of the local command itself, i.e. 0. If the code matters, split it: local x; x=$(cmd).
  • Unquoted $* and $@ split arguments on spaces. The argument "one two" turns into two. Write "$@".
  • set -e doesn't work inside a function called in a condition. With f || echo fail and if f; then, errors of commands inside f are ignored and the function runs to the end.
  • Only bash understands export -f. sh -c name says not found: sh on Ubuntu is dash.
  • source lib.sh looks for the file first in $PATH, then in the current directory — current for whoever launched the script, not the script's own directory. Run the script from somewhere else and the library won't be found. Use a path relative to the script: source "$(dirname "$0")/lib.sh".

See also

variables · exit-codes · getopts · set · conditions-loops