Defining and Calling Bash Functions

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 88 of 205

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:

PartMeaning
nameThe 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 if or while (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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Defining and Calling Bash Functions and get answers drawn from it.

Signed-in readers only.