Defining and Calling Bash Functions
A function is a named block of commands. You write the block once, give it a name, and then run it as often as you like by using the name like any other command. Functions remove repeated code, give meaningful names to the steps of a script and make a long script easier to read and change.
In Bash a function behaves like a small command that lives inside the shell. It runs in the current shell process, it can read and change the script's variables, it can receive arguments (lesson 89) and it returns a status code (lesson 90).
Syntax
There are two ways to define a function in Bash:
name() {
commands
}
function name {
commands
}
A third form, function name() { ... }, combines both and also works in Bash. The first form is the POSIX form. It runs in every POSIX shell, so it is the one to prefer when you have no reason to choose another.
The parts of the definition are:
| Part | Meaning |
|---|---|
name | The word you type later to run the function |
() | Marks the definition; it never holds parameters in Bash |
{ ... } | The body, a list of commands |
; or a newline before } | Required, so Bash knows where the last command ends |
Basic Example
greet() {
echo "Hello from a function"
}
greet
greet
Output:
Hello from a function
Hello from a function
The definition itself prints nothing. It only stores the body under the name greet. The two lines greet are the calls. Each call runs the stored body from the start. A function is called by its name alone, without parentheses. Writing greet() at a call site makes Bash expect a new definition, and the next line then fails with syntax error near unexpected token.
The function keyword form gives the same result:
function say_bye {
echo "Goodbye"
}
say_bye
Goodbye
Writing a Function on One Line
A short function can be written on one line, but then the closing brace must be preceded by a semicolon, and the braces must be separated from the commands by spaces:
hi() { echo hi; }
hi
hi
Bash treats { and } as reserved words, which are only recognized when they stand alone as words. These mistakes produce syntax errors, as printed by Bash 5.2.21 for a script file:
f() { echo hi } -> bad1.sh: line 3: syntax error: unexpected end of file
f() {echo hi; } -> bad2.sh: line 1: syntax error near unexpected token `{echo'
f() { } -> bad3.sh: line 1: syntax error near unexpected token `}'
In the first line, the closing brace is read as an argument of echo, so the function is never closed. In the second, {echo is one word. The third shows that a function body cannot be empty. If you need a placeholder, use the : command, which does nothing and succeeds:
f() { :; }
The brace may also be on its own line, which some programmers prefer:
f ()
{
echo "brace on next line"
}
How Bash Handles a Definition
When Bash reads a function definition, it stores the commands in memory and does not run them. Because of this, two facts follow.
A function must be defined before it is called. The shell reads the script from top to bottom. Calling a name before its definition fails:
later
later() { echo defined; }
later
bash: line 1: later: command not found
defined
The first call failed because later did not exist yet, and the second call worked.
A function may call another function that is defined after it, as long as both exist when the call runs. The name is looked up at the moment of the call, not when the definition is read:
outer() { inner; }
inner() { echo "inner ran"; }
outer
inner ran
outer mentions inner before inner is defined, but the call outer comes after both definitions. A common layout for larger scripts is therefore: definitions at the top, the main commands at the bottom (lesson 94).
Functions Share the Script's Variables
A function does not get a private copy of the script's variables. It runs in the same shell, so an assignment inside the function is visible after it returns:
counter=0
bump() { counter=$((counter + 1)); }
bump; bump; bump
echo "counter=$counter"
counter=3
This is convenient, and it is also a source of accidents, because a function can overwrite a variable of the caller by chance. The keyword local (lessons 92 and 93) limits a variable to the function.
Inspecting Functions
Bash can show you the functions that exist:
type greet
declare -F greet
declare -f greet
greet is a function
greet
greet ()
{
echo "Hello from a function"
}
type (lesson 14) identifies the name as a function, declare -F prints only the name of the function, and declare -f prints the full definition, reformatted by Bash. Used without a name, declare -F lists every function defined in the current shell. This is useful when you load a file of utility functions and want to see what it added.
Removing and Redefining a Function
unset -f deletes a function (lesson 41):
unset -f greet
greet
bash: greet: command not found
The exit status of that failed call was 127, the status for "command not found" (lesson 116).
Defining the same name again simply replaces the old body, and the new version is used from that point on:
v() { echo v1; }
v
v() { echo v2; }
v
v1
v2
Naming Functions
Function names follow looser rules than variable names. Bash accepts letters, digits, underscores, hyphens and dots, so my-func and my.func both work:
my-func() { echo "hyphen ok"; }
my-func
hyphen ok
Portable scripts should still use only letters, digits and underscores, because Dash rejects the hyphen form (see the section on portability below). Pick a name that says what the function does, and avoid the name of an existing command unless you intend to replace it.
Functions That Replace Commands
A function has a higher priority than a program of the same name. If you define a function called ls or echo, the shell runs your function instead of the real command. This can be used to wrap a command with extra behavior. To reach the original command from inside the wrapper, use command (for programs and builtins) or builtin (for builtins only):
echo() { builtin echo "[wrapped] $*"; }
echo hello
unset -f echo
echo "plain echo again"
[wrapped] hello
plain echo again
Without builtin, the function would call itself forever, because inside the body the name echo refers to the function again. The same idea works with a program:
ls() { command ls -1 "$@" | head -n 2; }
In a folder holding the files a, b and c, calling ls d88 printed
a
b
and type ls showed that ls was now a function. The "$@" passes all the function's arguments on to the real ls (lesson 89). After unset -f ls the original command came back. For most scripts, choose a new name for your function so that nobody is surprised by it.
A Function with a Subshell Body
The body is normally written with braces { }. It can instead be written with parentheses ( ), and then the whole body runs in a subshell (lesson 33), a separate copy of the shell:
count=10
inc_sub() ( count=$((count + 1)); echo "inside: $count" )
inc_sub
echo "outside: $count"
inside: 11
outside: 10
The change to count stays inside the subshell and the caller's value remains 10. This form is a compact way to run a function that changes its directory or variables without affecting the rest of the script. It starts a new process each time, so it is slower than the brace form.
Calling Functions in Different Places
A function call is a command, so it can be used wherever a command can:
- on its own line;
- in a pipeline (lesson 61);
- inside
$( )to capture its output (lesson 48); - as the condition of
iforwhile(lessons 66 and 80); - in a list with
&&and||(lesson 65).
In a pipeline and with captured output
shout() { echo "${1^^}"; }
msg=$(shout "quiet words")
echo "captured: $msg"
double() { while read -r n; do echo $((n * 2)); done; }
printf '1\n2\n3\n' | double
captured: QUIET WORDS
2
4
6
The function shout receives an argument, and ${1^^} turns it into upper case. The output of shout is stored in msg. The function double reads its numbers from standard input, so it can be placed at the end of a pipeline like any filter.
The status of a function
A function ends with the status of the last command it ran, and $? shows it right after the call:
fail() { false; }
fail; echo "status of fail: $?"
okf() { echo ran; }
okf >/dev/null; echo "status of okf: $?"
status of fail: 1
status of okf: 0
Lesson 90 explains how to choose the status deliberately with return.
A Recursive Function
A function can call itself. This is called recursion. Each call must move closer to a stopping case, or the calls would never end:
fact() {
local n=$1
if (( n <= 1 )); then
echo 1
else
echo $(( n * $(fact $((n - 1))) ))
fi
}
fact 5
120
For fact 5, the function calls fact 4, which calls fact 3, down to fact 1, which prints 1 and stops the chain. The results are multiplied on the way back: 1, 2, 6, 24 and 120. The local keyword gives each call its own copy of n (lesson 92). Because every $( ) starts a subshell, deep recursion in Bash is slow; a loop is usually the better tool.
Knowing Which Function Is Running
Inside a function, the array FUNCNAME holds the names of the active functions, and ${FUNCNAME[0]} is the current one:
who_am_i() { echo "inside: ${FUNCNAME[0]}"; }
who_am_i
echo "top level FUNCNAME=[${FUNCNAME[0]-}]"
inside: who_am_i
top level FUNCNAME=[]
At the top level of a script, FUNCNAME is empty. It is helpful in error messages and logs (lesson 125), because a message can say where it came from.
Defining Functions Conditionally
A definition is a command, so it can sit inside an if. Scripts use this to choose a version of a function that fits the environment:
if command -v tput >/dev/null 2>&1; then
note() { echo "tput found"; }
else
note() { echo "no tput"; }
fi
note
tput found
The output depends on the machine. command -v prints the path of a command and succeeds if the command exists, which makes it a handy test for "is this program available?".
Making a Function Available to Child Bash Processes
A function is part of the current shell, so a program started from the script does not know it. With export -f (lesson 38) the function is copied into the environment, and a child Bash process can use it:
hello_child() { echo "hello from exported function"; }
export -f hello_child
bash -c 'hello_child'
unset -f hello_child
bash -c 'hello_child'
hello from exported function
bash: line 1: hello_child: command not found
After unset -f removed the function, the exported copy was gone for later children too. Exported functions work only between Bash shells, and they carry some security risks (lessons 154 to 157), so use them sparingly.
Portability
The POSIX form name() { ...; } works in Dash and every other POSIX shell. The function keyword does not. Dash treats function as a normal word, so this definition fails:
function bye { echo bye; }
d88.sh: 3: Syntax error: "}" unexpected
Dash also rejects hyphens in function names:
my-func() { echo "hyphen"; }
d88b.sh: 1: Syntax error: Bad function name
Use the form name() with letters, digits and underscores for scripts that must run under sh. Lessons 188 and 189 collect these differences between Bash and POSIX syntax.