Functions play an important role in any programming language. Like many real programming languages, bash has functions which are used with limited implementation.

What are functions?
In programming, functions are named sections of a program that performs a specific task. In this sense, a function is a type of procedure or routine. When a function is called the program leaves the current section of code and begins to execute the first line inside the function. Whenever there is repetitive code or when a task repeats, consider using a function instead.
For example, consider the case where we need to find the factorial of a number at several stages of a particular program. Instead of writing the whole code (for calculating the factorial) each and every time, we can write that part of code which calculates the factorial once inside a block and reuse the same at multiple occasions.
Why do we write functions?
- It helps us to reuse the code.
- Improve the readability of program.
- Efficient use of variables inside the program.
- Allows us to test the program part by part.
- Displays program as a bunch of sub-steps.
Functions in shell scripts
The general syntax for writing functions in shell script includes the following ways.
You are always free to write valid commands inside these function blocks as we do normally in shell scripts. Now let’s try to write one simple script with a small function inside it.
The function definition must precede the first call to it. There is nothing like ‘declaring the function’ before calling it. And we can always nest functions inside functions.
Note:- Writing empty functions always results in syntax errors.
When same function is defined multiple times, the final version is what is invoked. Let’s take an example.
Functions taking parameters and returning values
Let’s get deeper by considering functions taking parameters and returning values. To return a value from a function we use the ‘return’ shell built-in. Syntax is as follows.
Similarly we can pass arguments to the functions separated with spaces as given below.
Inside the function we can access the arguments in order as $1, $2, $3 and so on. Look at the following example script to find the maximum of two integers using function to add more clarity.
The above looks like a bit complex, but it’s simple if we read through the lines. First nested if-else if lines for validation purposes i.e., to check number and type of arguments with the help of regular expressions. After that we call the function with two command line arguments and displays the result there itself. This is because we cannot return large integers from a function. Another way to work around this problem is to use global variables to store the result inside function. The script below explains this method.
No comments:
Post a Comment