Functions bundle a set of commands into a named unit you can call multiple times.
# Form 1: name() { ... }
greet() {
echo "hello, $1"
}
# Form 2: function name { ... }
function greet {
echo "hello, $1"
}
Both work. The first is POSIX-standard and more common. Use it.
greet alice
greet "Bob Smith"
Call like any other command. No parentheses, no special syntax.
Inside a function, $1, $2, $#, $@, and $* refer to
the function's arguments, not the script's. The script's
arguments are shadowed while inside the function.
say_all() {
echo "got $# args"
for arg in "$@"; do
echo "- $arg"
done
}
say_all one two three
# got 3 args
# - one
# - two
# - three
$0 still refers to the script name, not the function name.
Bash reads scripts top to bottom. A function must be defined before it's called:
# WRONG
greet alice
greet() { echo "hello, $1"; }
# RIGHT
greet() { echo "hello, $1"; }
greet alice
The common convention is to define all functions at the top of the script, then run the main logic below.