Course Overview

/

Bash Functions

Functions

By introducing functions into a script it is possible to create small sections of code that perform a specific task. Functions are used to make code more modular, easier to read, and easier to reuse. By dividing a program into smaller, independent functions, it becomes easier to understand and maintain the program as a whole.

In Bash a function is defined by writing the function name followed by a pair of parentheses .

One of the benefits to using functions is the ability to write code once and call it in multiple locations throughout a script. It is also possible to combine functions together to create more advanced actions without having to add too much complexity to the scripting process.

2nd Bash Script

The second bash script created is:

These functions provide small code segments that will conduct an action with the variable provided

Function 1

Function 1 is a simple echo command with the output of x multiplied by y. The function is defined and named using the line

This sets the name of the function as “function 1” and it is executed by simply calling the function

Function 2

Function 2 introduces the use of a string parameter. The function is defined the same was as before, it should be noted that we do not need to define the names or numbers of parameters when creating bash functions. When a function is called Bash will automatically create a set of positional parameters represented by the variables $1, $2, $3, etc.

This allows the creation of a function that uses $1 with the line. As the echo command is using both a string output and a parameter, we need to use quotation marks to define where the string value starts and ends. To add a parameter value to the middle of a string means we need to break our text into two parts as seen below.

and declare the value of the parameter when we call the function. This can be seen below

Function 3

Function 3 demonstrates the simple method used to create a function with multiple parameters and further demonstrates the use of $1, $2, $3, etc. as values that are used when parameter values are being passed to a function.