LESSON · 1 OF 5

Defining and calling functions

Defining and calling functions

Functions bundle a set of commands into a named unit you can call multiple times.

The two syntax forms

bash
# 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.

Calling

bash
greet alice
greet "Bob Smith"

Call like any other command. No parentheses, no special syntax.

Function arguments

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.

bash
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.

Define before you call

Bash reads scripts top to bottom. A function must be defined before it's called:

bash
# 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.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute