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
| Notation | What 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 N | shift the arguments: $2 becomes $1 and so on |
$0 | name 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
| Notation | What it does |
|---|---|
x=1 | without a declaration the variable is global: visible and modifiable across the whole script |
local x=1 | the variable is visible only in this function and in the functions it calls |
local -a arr / local -A map / local -i n | local array / associative array / integer |
declare x=1 (inside a function) | same as local |
declare -g x=1 | an explicitly global variable from inside a function |
How to return a result
| Method | Example | When |
|---|---|---|
| exit code | return 0 / return 1 | "yes/no", "success/failure"; a number 0–255 |
| print to stdout | echo "$res", then x=$(f) | return a string or a number |
| global variable | RESULT=… | no subshell, but the function and the caller are coupled |
| variable reference | local -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
| Command | What it does |
|---|---|
declare -F | list names of declared functions |
declare -f name / type name | show a function's body |
unset -f name | delete a function |
export -f name | pass a function to child bash processes |
source file / . file | run 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 overwritesiin an outer loop. Declare working variables withlocal. returnis only a code 0–255.return 300returns44(the remainder of division by 256). Return strings and large numbers viaechoand$(…).- 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 andcdinside it don't leak out.local x=$(cmd)loses the exit code ofcmd.$?after such a line is the code of thelocalcommand 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 -edoesn't work inside a function called in a condition. Withf || echo failandif f; then, errors of commands insidefare ignored and the function runs to the end.- Only bash understands
export -f.sh -c namesaysnot found:shon Ubuntu isdash. source lib.shlooks 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