Bash Functions
Updated on
•6 min read

A Bash function is a reusable block of commands that can be called multiple times within a script. Functions help you make your Bash scripts more readable, easier to maintain, and less repetitive.
While Bash functions are more limited than those in other programming languages, they are still very powerful for shell scripting.
In this guide, we will cover the basics of Bash functions and show you how to use them in your shell scripts. If you’re new to Bash, consider reviewing the basic Linux commands first.
Defining Bash Functions
There are two different ways to define a function in Bash.
Preferred Syntax (Most Common) The first format starts with the function name, followed by parentheses. This is the preferred and most-used syntax.
shfunction_name () { commands }Single line version:
shfunction_name () { commands; }Using the
functionKeyword The second format starts with the reserved wordfunction, followed by the function name.shfunction function_name { commands }Single line version:
shfunction function_name { commands; }
Important points to note:
- The commands inside the curly braces (
{}) make up the function body. - The opening and closing braces must be separated from the body by spaces or newlines.
- A function runs only when explicitly called by name.
- The function must be defined before it is called.
- When using single-line “compacted” functions, a semicolon
;is required after the last command. - Use descriptive function names whenever possible.
function_name () {}) for better portability and readability.Example: Hello World Function
To understand this better, take a look at the following example:
#!/bin/bash
hello_world () {
echo 'Hello, World.'
}
hello_worldLet’s analyze the code line by line:
- In line 3, we are defining the function by giving it a name. The curly brace
{marks the start of the function’s body. - Line
4is the function body. The function body can contain multiple commands, statements, and variable declarations. - Line
5, the closing curly bracket}, defines the end of thehello_worldfunction. - In line
7, we are executing the function. You can execute the function as many times as you need.
Running the script prints:
Hello, World.You can call the function as many times as needed within the script.
Variable Scope in Bash Functions
Knowing how variable scope works helps you write scripts that are safe and predictable.
Global Variables
- Global variables are variables that can be accessed and modified anywhere in the script, including inside functions.
- By default, all variables are defined as global, even if declared inside the function.
Local Variables
- Local variables are declared with the
localkeyword. - Local variables can be declared only inside the function and can be used only inside that function.
- You can have local variables with the same name in different functions.
- Local variables override global variables with the same name within the function.
Example: Variable Scope
To better illustrate how variable scope works in Bash, let’s consider this example:
#!/bin/bash
var1='A'
var2='B'
my_function () {
local var1='C'
var2='D'
echo "Inside function: var1: $var1, var2: $var2"
}
echo "Before executing function: var1: $var1, var2: $var2"
my_function
echo "After executing function: var1: $var1, var2: $var2"The script starts by defining two global variables var1 and var2. Then there is a function that sets a local variable var1 and modifies the global variable var2.
If you run the script, you should see the following output:
Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: DFrom the output above, we can conclude that:
- When a local variable is defined within a function with the same name as an existing global variable, the local variable takes precedence.
- Global variables can be changed from within the function.
Return Values in Bash Functions
Unlike functions in “real” programming languages, Bash functions do not return values when called.
When a bash function completes, its return value is the status of the last statement executed in the function:
0for success.- Any non-zero value in the (1 - 255) range for failure.
The return status can be specified using the return keyword, and it is assigned to the variable $?. The return statement terminates the function. You can think of it as the function’s exit status
.
#!/bin/bash
my_function () {
echo "some result"
return 55
}
my_function
echo $?some result
55Returning Data from a Bash Function
Since Bash cannot return arbitrary values directly, we need to use other methods. There are two common workarounds.
Using a Global Variable:
The simplest option is to assign the result of the function to a global variable:
~/return_values.shsh#!/bin/bash my_function () { func_result="some result" } my_function echo $func_resultoutputsome resultUsing Standard Output (Recommended)
Another option is to send the value to
stdoutusingechoorprintf. This approach is cleaner and avoids unnecessary global variables:~/return_values.shsh#!/bin/bash my_function () { local func_result="some result" echo "$func_result" } func_result="$(my_function)" echo $func_resultoutputsome resultInstead of simply executing the function, which prints the message to
stdout, we assign the function’s output to thefunc_resultvariable using the$()command substitution. The variable can later be used as needed.
Passing Arguments to Functions
Arguments are passed to a function by placing them after the function name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it.
function_name arg1 arg2 arg3Special Variables
- Positional parameters
$1,$2,$3…$n, correspond to the position of the parameter after the function’s name. - The
$0variable is reserved for the function’s name. - The
$#variable holds the number of positional parameters/arguments passed to the function. - The
$*and$@variables hold all positional parameters/arguments passed to the function.- When double-quoted,
"$*"expands to a single string separated by space (the first character of IFS) -"$1 $2 $n". - When double-quoted,
"$@"expands to separate strings -"$1" "$2" "$n". - When not double-quoted,
$*and$@are the same.
- When double-quoted,
Here is an example:
#!/bin/bash
greeting () {
echo "Hello $1"
}
greeting "Zoe"Hello ZoeBash Function Best Practices
- Choose function names that clearly describe what the function does.
- Declare variables as local inside functions to avoid unexpected behavior.
- Return the data via standard output rather than relying on global variables.
- Be sure to quote variables, such as “
$var”. - Write functions that are short and handle only one specific task.
- Put your function definitions at the top of your scripts.
- Turn on
set -euo pipefailwhen writing scripts for production. - Add comments to explain any complex logic inside your functions.
Conclusion
A Bash function is a block of reusable code designed to perform a particular operation. Once defined, the function can be called multiple times within a script.
Functions are especially useful for repeating tasks, simplifying complex scripts, and creating readable and modular code.
You can also read about how to use a Bash function to create a memorable shortcut command (alias) for a longer command. For more details on executing scripts, see our guide on how to run a bash script .
If you have any questions or feedback, feel free to leave a comment.


