A Comprehensive Guide To Using Bash Functions In Your Scripts

Try this guide with our instant dedicated server for as low as 40 Euros

bash function

Bourne Again Shell, or bash, is a widely used command processor that allows users to interact with the operating system (usually Linux) through bash commands. Advanced users can combine these commands in scripts that automate regular tasks.

In addition to single-use statements, bash scripts rely upon bash functions to simplify the structure and increase the usability.

In this article, we’ll explore bash functions and how you can use them in your scripts. After going through this short tutorial, you can confidently write bash functions and enhance the overall effectiveness of your scripts.

Let’s start with an overview of bash functions.

Table Of Content

  1. What Are Bash Functions?
  2. How to Use Bash Functions?
    1. Prerequisites
    2. Basic Bash Function Syntax
    3. How to Define and Execute Functions
    4. Step 1: Create a Bash Script
    5. Step 2: Add the Function Definition
    6. Step 3: Save the Script and Exit the Editor
    7. Step 4: Grant Execution Permissions
    8. Step 5: Run the Script
    9. How to Declare and Run a Function Directly in the Terminal
    10. Step #1: Log in to the SSH Terminal
    11. Step #2: Execute the Function
    12. Locating the Definition and Contents of a Bash Function
    13. Step #1: Enter Bash Debugger Mode
    14. Step #2: Check the Function’s Source File
    15. Step #3: View the Function’s Contents
    16. Deleting a Bash Function
  3. Bash Function Variables and Dynamic Scoping
    1. Step #1: Create a Bash Script
    2. Step #2: Add the Script Code
    3. Step #3: Save the Script and Exit the Editor
    4. Step #4: Make the Script Executable
    5. Step #5: Run the Script
  4. Passing Arguments to Bash Functions
    1. Step #1: Create a Bash Script
    2. Step #2: Add the Code
    3. Step #3: Save and Exit the Script
    4. Step #4: Make the Script Executable
    5. Step #5: Run the Script
  5. The Idea of Return in Bash Functions
    1. Step #1: Create a Bash Script
    2. Step #2: Add the Code
    3. Step #3: Save the Script and Exit
    4. Step #4:. Make the Script Executable
    5. Step #5:. Run the Script
  6. Conclusion
  7. FAQs

What Are Bash Functions?

Bash functions are the building blocks of modular and reusable code. Developers use them to simplify the script’s structure and syntax. Users use bash functions to group reusable code segments under a specific name for convenient usage. In effect, these functions act like a script within a script.

Here’s a bash script that has a function named hello_world(). The main statement of the script calls the function that prints the Hello, world! message.

bash function script

Using these functions in bash scripting offers two significant benefits:

  • Functions are directly loaded into the shell’s memory and stored for future use. Given the abundant memory available today, utilizing functions ensures faster execution than duplicating code.
  • Functions aid in organizing lengthy shell scripts by breaking them down into modular and reusable code blocks. This approach makes script development and maintenance more manageable and straightforward.

How to Use Bash Functions?

Let’s see how you can use bash functions in your scripts.  

Prerequisites

Before working with bash scripts, you’ll need: 

  • Basic understanding of bash scripting
  • Access to a Unix-based system (Linux/Mac) or a Unix-compatible environment on Windows (like WSL)

Bash functions are very flexible and promote code reusability. As such, users can implement them in two ways:

  • Within a Shell Script: Here, the user defines the function within the script, ensuring the function definition precedes any calls to the function.
  • Alongside Bash Alias Commands or Directly in the Terminal: Users can also declare functions and use them directly in the terminal or incorporate them with other bash alias commands.

Now that you know where to add the functions and their definitions, let’s jump into syntax guidelines.

Basic Bash Function Syntax

There are two primary formats for declaring a bash function:

Format #1

<function name> () {
<commands>
}

Alternatively, the same function can be declared in a single line:

<function name> () { <commands>; }

Format #2

function <function name> {
<commands>
}

Or in a compact one-line format:

function <function name> { <commands>; }

Consider the following tips for writing better bash functions:

  • Make sure the one-liner format ends with a semicolon (;) in bash scripts and the terminal.
  • The reserved word ‘function’ allows optional parentheses when declaring a function.
  • The commands and statements within the curly braces { <commands> } are called the function’s body. The body can include various declarations, variables, loops, and conditional statements.
  • Always use descriptive names for bash functions. Meaningful names improve code readability and help other users and testers understand the purpose of the functions, especially in collaborative code-writing settings.

Also Read: How to Read Files Line by Line in a Bash Script [5 Simple Methods Inside!]

How to Define and Execute Functions

Declaring a function in a bash script doesn’t trigger its execution. Instead, the function’s body is executed when it is called in the main body of the script. Here’s a detailed overview of the process of creating and executing a bash function in a script:

Step 1: Create a Bash Script

Launch your preferred text editor to create a shell script named syntax.sh. We’ll use Vim for this demonstration. 

Start by running the following command in the SSH terminal:

vim syntax.sh

Step 2: Add the Function Definition

Add the following code to the script document:

# syntax.sh
# Declaring functions using the reserved word function
# Multiline
function f1 {
echo "Hello, I'm function 1"
echo "good bye!"
}
# One line
function f2 { echo "Hello, I'm function 2"; echo "good bye!"; }

# Declaring functions without the function reserved word
# Multiline
f3 () {
echo "Hello, I'm function 3"
echo "good bye!"
}
# One line
f4 () { echo "Hello, I'm function 4"; echo "good bye!"; }

# Invoking functions
f4
f3
f2
f1

Step 3: Save the Script and Exit the Editor

Save the changes and close the editor. We’re using Vim, and we’ll exit the editor with the Esc >> :wq command:

:wq

Step 4: Grant Execution Permissions

For security reasons, files such as scripts don’t have execute permission. You can change syntax.sh file permissions with the following command:

chmod +x syntax.sh

Step 5: Run the Script

Simply call the script to see the output:

./syntax.sh

The script works as follows:

  • Lines 4-9 showcase function definitions with the function keyword, presenting a multi-line syntax for f1 (lines 4-6) and a one-line syntax for f2 (line 9). 
  • Lines 13-18 display a standard function definition with f3 as a multi-line function (lines 13-16) and f4 (line 18) as its single-line counterpart. 
  • Finally, lines 21-24 execute the defined functions in reverse order of their definition, running the commands within each function.

bash functions syntax

IF-ELSE statement blocks introduce decision-making capabilities in bash scripts. Read this comprehensive introduction to IF-ELSE statements in shell scripting to add more power to your scripts. 

How to Declare and Run a Function Directly in the Terminal

You can also directly define and execute bash functions in the terminal. A typical process has the following steps:

Step #1: Log in to the SSH Terminal

Launch the terminal and enter the following line to define the function:

$ my_function () { echo "Hello, I'm a function"; echo "good Bye\!"; }

Step #2: Execute the Function

 Execute the function by typing its name in the terminal:

$ my_function

my bash function script

The output displays the execution of commands within the function’s body.

Important: The function definition remains available for the duration of the current terminal session. When you exit the session, the definition is lost. We recommend adding the code to the ~/.bashrc file to ensure function definition persistence in future sessions.

Locating the Definition and Contents of a Bash Function

Often, you need to find out the definition and contents of a bash function to understand its operation and edit if required. The process has the following steps: 

Step #1: Enter Bash Debugger Mode

Launch the bash shell in debugger mode with the following command:

$ bash --debug

Step #2: Check the Function’s Source File

Use the declare -F <function name> command to inspect the location and content of the source file and location. Replace <function name> with the actual function name.

$ declare -F my_function

The output displays the function’s name, line number, and file location.

Step #3: View the Function’s Contents

Use the declare -f <function name> command to view the function’s contents. Replace <function name> with the actual function name.

$ declare -f my_function

declare bash function

In debugging mode, the built-in declare directive allows for inspecting the function’s contents and location without executing the script’s code.

Deleting a Bash Function

There are times when you want to reclaim the namespace taken by a function in the ongoing terminal session. For this, use the following command to “delete” a function’s definition:

$ unset <function name>

For instance, here’s how you can delete the my_function() you declared earlier:

$ unset my_function

unset - deleting bash function

When this command is executed, the function will be removed and no longer accessible within the current terminal session. If the function is available/defined in the ~/.bashrc file, it will be restored in subsequent sessions, returning everything to its previous state.

Do you know that the .bashrc file plays a critical role in terminal management and operations? Read more about this file in our detailed introduction to the .bashrc file.

Bash Function Variables and Dynamic Scoping

In bash scripting, variables are global by default and can be accessed anywhere, including within function bodies. Similarly, variables declared within a function are typically treated as global. 

However, you can use the local keyword if you need to limit the scope of variables to the function’s body. Note that when a variable is declared as local, subsequent child functions or processes can access it. 

In dynamic scoping, a local variable takes precedence over a global variable when they share the same name.

The following steps illustrate how bash function variables and dynamic scoping work:

Step1: Create a Bash Script

Use your preferred text editor to create a script named variable.sh. Since we’re using Vim, run the below command:

$ vim variable.sh

Step2: Add the Script Code

Add the following code to the script:

var1=1
var2=1
change() {
echo "Inside function"
echo "Variable 1 is: $var1"
echo "Variable 2 is: $var2"
local var1=5
var2=5
echo
echo "After change inside function"
echo "Variable 1 is locally $var1"
echo "Variable 2 is globally $var2"
}
echo "Before function invocation"
echo "Variable 1 is: $var1"
echo "Variable 2 is: $var2"
echo
change
echo
echo "After function invocation"
echo "Variable 1 is: $var1"
echo "Variable 2 is: $var2"

The script demonstrates the behavior of function variables and dynamic scoping.

Step3: Save the Script and Exit the Editor

Save the changes and exit the editor (for Vim, type Esc:wq).

Step #4: Make the Script Executable

Allow script execution by granting the necessary permissions:

$ chmod +x variable.sh

Step #5: Run the Script

Execute the script and observe the output:

$ ./variable.sh

variable bash function script command output

The script will display variable values before and after calling the function, showcasing the changes made by the script.

Passing Arguments to Bash Functions

Users can pass arguments to a function when calling it by specifying the parameters after the function call (separated by spaces). Parameters are very flexible, and users have a lot of latitude when using these parameters.

The following table provides an overview of the bash function argument options:

Argument Role
$0 Represents the function’s name when defined in the terminal. When defined in a bash script, $0 returns the script’s name and location.
$1, $2, etc. Correspond to the argument’s position following the function name.
$# Holds the count of positional arguments passed to the function.
$@ and $* Represent the positional arguments list, treating them the same when used this way.
“$@” Expands the list to separate strings, for example, “$1”, “$2”, etc.
“$*” Expands the list into a single string, separating parameters with a space, for example, “$1 $2”, etc.

Let’s explore how arguments work within a bash script. Here are the typical steps in the process:

Step-1: Create a Bash Script

Use your preferred text editor to create a script named arguments.sh. If you’re using Vim, run the following command:

$ vim arguments.sh

Step-2: Add the Code

Add the following code to the file:

arguments () {
echo "The function location is $0"
echo "There are $# arguments"
echo "Argument 1 is $1"
echo "Argument 2 is $2"
echo "<$@>" and "<$*>" are the same.
echo "List the elements in a for loop to see the difference!"
echo "* gives:"
for arg in "$*"; do echo "<$arg>"; done
echo "@ gives:"
for arg in "$@"; do echo "<$arg>"; done
}

arguments hello team

The script demonstrates the behavior of various function arguments.

Step-3: Save and Exit the Script

Save the changes and exit the editor (for Vim, type Esc:wq).

Step-4: Make the Script Executable

Grant execution permissions to the script:

$ chmod +x arguments.sh

Step-5: Run the Script

Execute the script and observe the output:

$ ./arguments.sh

arguments bash function script

The script will display descriptive messages for each argument, showcasing their roles and values.

The Idea of Return in Bash Functions

In bash scripting, the idea of returning a value from a function is very different from the return functionality of most programming languages. By default, bash returns the exit status of the last command executed within the function’s body.

Let’s take a closer look at how the exit status using return works in a bash function. The process has the following steps: 

Step #1: Create a Bash Script

Use your preferred text editor to create a script named test.sh. If using Vim, run the following command:

$ vim test.sh

Step #2: Add the Code

Insert the following code into the file:

test_function() {
echo "Test"
return 100
}

echo "The function's output is:"
test_function
echo "The exit status is:"
echo $?

The script illustrates how to specify the return status using return.

Step #3: Save the Script and Exit

Save the changes and exit the editor (for Vim, type Esc:wq).

Step #4: Make the Script Executable

Grant execution permissions to the script:

$ chmod +x test.sh

Step #5:. Run the Script

Execute the script to observe the function’s output and exit status:

$ ./test.sh

test bash function script

The script will display the function’s output and the specified exit status.

An alternative approach involves echoing the function’s result with the help of an echo function and assigning it to a variable. To see this idea in action, modify the test.sh script with the following code:

test_function() {
echo "Test"
}
result=$(test_function)
echo "$result is saved in a variable for later use"

This method emulates the behavior of functions in most programming languages by allowing the result to be stored in a variable for further use.

Conclusion

Bash functions are crucial in writing structured, reusable scripts in Unix-based systems. Understanding how to declare, invoke, and manage functions, along with their variables, arguments, and return values, is fundamental to efficient Bash scripting. 

Using the echo statement in the functions aids in generating desired output and enhancing script functionality. For more complex operations, incorporating return statements and exploring recursive functions can further optimize script flow and performance. 

Whether executing a single task or managing an entire script file, leveraging the power of functions is crucial to creating reliable and scalable Bash scripts. 

You need a dependable server infrastructure that is optimized for your preferred OS and software stack. This is where RedSwitches comes into the picture. We offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What does the term ‘bash function’ mean?

A bash function is a collection of commands grouped together, accessible by calling its designated name.

Q. What steps are involved in creating a bash function?

To create a bash function, you define it using the function keyword, followed by the function name, optional parentheses for arguments, and a block of code enclosed in curly braces.

Q. How can one define the syntax for a bash function?

The syntax for defining a bash function is as follows:

function_name() {
# code goes here
}

Q. How do I pass arguments to a bash function?

You can pass arguments to a bash function by including them inside the parentheses after the function name. Within the function, you can access these arguments using special variables like `$1`, `$2`, etc., representing the first, second, and rest of the arguments passed to the function.

Q. What’s the method to fetch the return value from a bash function?

To obtain the return value of a bash function, utilize the return statement within the function to set the desired value. Subsequently, after calling the function, employ the special variable $? to access the returned value in a straightforward manner, effectively reversing the process. Additionally, utilizing the function echo to convey the intended return value is another approach to facilitate seamless retrieval.

Q. What is the variable scope within a bash function?

Variables defined within a bash function have local scope, and are only accessible within that function. Similarly, variables defined outside a function have global scope. As a result, any function or command within the script can access them.

Q. How do I use local variables in a bash function?

You can use local variables in a bash function by using the `local` keyword before the variable name. This ensures that the variable is only accessible within the function and does not interfere with global variables of the same name.

Q. Can a bash function be defined using the same name as an existing command?

Indeed, you can define a bash function with the same name as an existing command. Upon calling the function, it will execute in place of the command with the matching name.

Q. How do I use descriptive names for my functions in bash scripting?

To use descriptive names for your functions in bash scripting, you can choose any name that reflects the purpose or functionality of the function. We recommend using meaningful names to make your code more readable and maintainable.

Q. Is it possible to pass command line arguments to a bash function?

Yes, you can pass command line arguments to a bash function by accessing them using unique variables like `$1`, `$2`, etc. These variables represent the command line arguments passed to the script, and you can use them within the function.

Q. In what scenarios are bash functions frequently applied?

Bash functions are commonly used for code reusability, modular programming, and improving the organization and readability of bash scripts. They can be created to perform specific tasks, handle repetitive operations, or encapsulate complex logic within a single function.

Try this guide with our instant dedicated server for as low as 40 Euros