Bash Functions (original) (raw)

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.
Defining Bash Functions
There are two different ways to define a function in Bash.
- The first format starts with the function name, followed by parentheses. This is the preferred and most used syntax.
function_name () {
commands
} Single line version:
function_name () { commands; } - The second format starts with the reserved word
function, followed by the function name.
function function_name {
commands
} Single line version:
function 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.
Example: Hello World Function
To understand this better, take a look at the following example:
~/hello_world.sh
#!/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:
Variable Scope in Bash Functions
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:
~/variables_scope.sh
#!/bin/bash
var1='A'
var2='B'
my_function () {
local var1='C'
var2='D'
echo "Inside function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"
}
echo "Before executing function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"
my_function
echo "After executing function: var1: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>v</mi><mi>a</mi><mi>r</mi><mn>1</mn><mo separator="true">,</mo><mi>v</mi><mi>a</mi><mi>r</mi><mn>2</mn><mo>:</mo></mrow><annotation encoding="application/x-tex">var1, var2: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">1</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord">2</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>var2"
The script starts by defining two global variables var1 and var2. Then there is an 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: D
From 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.
~/return_values.sh
#!/bin/bash
my_function () {
echo "some result"
return 55
}
my_function
echo $?
some result
55
Returning Data from a 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.sh
#!/bin/bash
my_function () {
func_result="some result"
}
my_function
echo $func_result some result - Using Standard Output (Recommended)
Another option is to send the value tostdoutusing echoor printf. This approach is cleaner and avoids unnecessary global variables:
~/return_values.sh
#!/bin/bash
my_function () {
local func_result="some result"
echo "$func_result"
}
func_result="$(my_function)"
echo $func_result some result Instead of simply executing the function, which prints the message to stdout, we assign the function’s output to the func_result variable 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 arg3
Special 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 <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>2</mn></mrow><annotation encoding="application/x-tex">2 </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6444em;"></span><span class="mord">2</span></span></span></span>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:
~/passing_arguments.sh
#!/bin/bash
greeting () {
echo "Hello $1"
}
greeting "Zoe"
Hello Zoe
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.
If you have any questions or feedback, feel free to leave a comment.
If you like our content, please consider buying us a coffee.
Thank you for your support!
Sign up to our newsletter and get our latest tutorials and news straight to your mailbox.