Skip to content

Bash Functions: How to Write and Use Them (with Examples)

2 min read

Applies to: Bash 5 on Linux and macOS (examples tested with Bash 5.1)

A Bash function is a named block of commands you can call like a small command. Functions make scripts shorter, easier to read and easier to change. Every example here was run in Bash 5.1.

Define and call a function

greet() {
    local name="${1:-world}"
    echo "Hello, $name"
}

greet            # Hello, world
greet Ucartz     # Hello, Ucartz

Define a function before you call it. The keyword form function greet { ... } also works in Bash, but greet() { ... } is more portable.

Arguments

  • $1, $2...: the first, second argument.
  • $#: the number of arguments.
  • "$@": all arguments, each kept separate (use this to pass them on).
count_args() { echo "got $# arguments: $*"; }
count_args a "b c" d      # got 3 arguments: a b c d

Return values

return only sets an exit status (0 = success, 1 to 255 = failure). To give back data, print it and capture it:

add() { echo $(( $1 + $2 )); }
sum=$(add 2 3)
echo "sum=$sum"          # sum=5

backup_file() {
    local src="$1"
    [ -f "$src" ] || { echo "no such file: $src" >&2; return 1; }
    cp -- "$src" "$src.bak" && echo "saved $src.bak"
}
backup_file /nonexistent; echo "exit status: $?"   # exit status: 1

Send error messages to standard error (>&2), so they don’t end up in a variable that captures the output.

Local and global variables

Variables inside a function are global unless you mark them local:

x=outer
change() { local x=inner; y=global; }
change
echo "x=$x y=$y"       # x=outer y=global

Use local for everything a function uses internally, so it can’t overwrite variables elsewhere in the script.

List and reuse functions

declare -F                  # names of defined functions
declare -f greet            # show a function's code
source ~/lib/functions.sh   # load functions from a file

Put functions you use often in a file and source it from your scripts or from ~/.bashrc (Bash startup files).

Tips

  • Quote variables ("$1") so that names with spaces don’t break.
  • Start scripts with set -euo pipefail to stop on errors, unset variables and failed pipes.
  • Check scripts with shellcheck (available in most distributions’ repositories).

Related services

KVM VPS hosting

NVMe SSD and full root access, with Free Basic Managed Support.

Unmanaged dedicated servers

full root access and free IPMI KVM, with Free Basic Managed Support.

Linux server management

hardening, patching, monitoring and automation for Ubuntu, Debian, RHEL and AlmaLinux.

Was this answer helpful?

Still stuck? Open a ticket