Bash Functions | Explained

Bash scripting is a common way to automate processes in Linux in which the functions play an integral role. The main purpose of functions is to reuse the code repeatedly by calling the function to perform that task which prevents the users from writing the code several times.

This tutorial will cover the basics of Bash functions and demonstrate how to use them with the following timeline:

Let’s start with the introduction of functions.

What is a Function in Linux?

In Bash, functions execute several commands sequentially. A function is a block of code that is defined with a name and can be called using that name. When a function is called, it is executed with the given arguments.

The function has the following advantages:

  • Reusability: Avoid code duplication.
  • Readability: Avoids lengthy codes but divides complex code into small functions.
  • Debugging: Functions are easier to understand, maintain, and debug.
  • Execution Time: Function execution time is less than normal code execution.

The general syntax of the function is shown below:

function-name () {
    Commands to execute
}

The above function is also used in a single-line format such as:

function-name () { Commands to execute; }

Another method of declaring a function is to use the “function” keyword, such as:

function function-name {
       Commands to execute
}

The single-line syntax for the second format is:

function function-name { Commands to execute; }

How to Use Functions in Bash?

The functions are used in several ways according to requirements in bash. This section will discuss the common usage of the functions in bash.

Basic Usage of Function in Bash

The basic usage of the function is to create a reusable code that can be called repeatedly to perform a specific function rather than writing the whole code. For instance, if we want to create a function that only displays the text, utilize the below-written function:

#!/bin/bash
function test {
echo "Test output for a function!"
}

test

Let’s understand the above function line by line:

  • First Line shows that it’s a bash code.
  • The function keyword specifies that the function starts with its name, “test”.
  • A function’s body is defined within the curly braces { }. The { starts the body of the function while the } ends the function body.
  • The commands within the { } are executed to perform the required task.
  • The last test is used to call the above function, which will execute the command (echo) in the function.

The single-line format for the above function is:

#!/bin/bash
function test { echo "Test output for a function!"; }
test

Let’s execute the above simple bash function to check its output:

$ bash function.sh

The function is executed and shows the output for the “echo” command within the body.

How to Use Global Variables in Bash Function?

A bash function uses two types of variables: global and local. The global variables are written outside the body of the function, which can be accessed anywhere in the code. For instance, the below code has two global variables, “var1” and “var2”, which can be used inside and outside the function (in this case it is used inside the sum function to add these numbers):

#!/bin/bash
var1=3;
var2=5
function sum {
echo "Two numbers $var1 and $var2 sum is: $(($var1+$var2))"
}

sum

To check the bash script output, run the following command:

$ bash function.sh

The output shows the sum of the global variables.

How to Use Local Variables in Bash Function?

The local variables are defined and used within the body of the function. If the local variables are called outside the function, it will not work. For instance, the two local variables “var1” and “var2” are declared in the product function to multiply both numbers:

#!/bin/bash
function product {
var1=2;
var2=6
echo "Two numbers $var1 and $var2 product is: $(($var1*$var2))"
}

product

To check the output for the above script, use this command:

$ bash function.sh

The local variables are accessed within the function to multiply.

How to Use Arguments in Bash Function?

Passing arguments to a function is the common method that makes a function interactive. To pass the arguments to a specific function, we just need to write those arguments with the function name. For example, to pass two specific numbers (5 and 2) to a function as arguments for summing those numbers, the below command is used:

#!/bin/bash
function sum {
    result=$(($1+$2))
    echo "Sum of $1 and $2 is $result"
}

sum 5 2

For executing the above bash function with arguments, utilize the below-written command in the terminal:

$ bash function.sh

The arguments 5 and 2 are successfully passed to the “sum” function.

How to Take User Input in Bash Function?

The functions can be made more interactive and user-friendly by using the user input to execute a specific function. The “read” command allows the user input. The below function named “product” will take two numbers from the user and multiply them to save its result in the “result” variable by displaying them using the “echo” command:

#!/bin/bash
function product {
read -p "Enter 1st number: " num1
read -p "Enter 2nd number: " num2
    result=$(($num1*$num2))
    echo "Product of $num1 and $num2 is $result"
}

product

For running the above bash code, utilize this command:

$ bash function.sh

The output shows that the user inputs the “12” and “5”, which are multiplied and displayed on the output.

How to Return Value From Bash Function?

The function can also be used to return the value, which can be captured using the “$?” command. For instance, the below function is returning the value “12”, which can be utilized by using the “echo $?” to get the function return value:

#!/bin/bash
function test {
    echo "Function return Value is: "
       return 12
}

test
echo $?

To execute this script, use:

$ bash function.sh

The output shows that “12” is returned from the above function.

How to Delete a Bash Function?

Sometimes we need to delete a declared function which can be done using the unset keyword. For instance, to remove the sum function from the system, the below-written command is utilized:

$ unset <function-name>

Additional Tip: Add a Function Permanently Using .bashrc File

The functions can be utilized in the .bashrc startup file when the system starts up to perform specific tasks. The function is .bashrc files can also be utilized to create the bash aliases. To add a function permanently in the .bashrc files, these steps will be followed:

Open the .bashrc file with the sudo privileges:

$ sudo nano .bashrc

Add the desired function in this .bashrc file:

function UpdateUpgrade () {
sudo apt update -y
sudo apt upgrade -y
}

Use the “source” command to save the changes:

$ source .bashrc

Write the function name in the terminal to execute:

$ UpdateUpgrade

That’s all about the functions in Bash.

Conclusion

Bash functions in Linux are a useful way to organize and reuse code, which can help make your scripts more readable and modular. We can use local and global variables in functions. Moreover, the arguments can be passed to the functions, or the user input can be taken to make the function interactive. If you want to create aliases or perform specific tasks on startup, add the functions to the “.bashrc” file as performed in this tutorial.