The course is part of this learning path
In this Course, you'll learn why and when you'll want to use functions. You'll learn how to create functions as well as how to use them. We'll talk about variables and their scope and how that applies to functions. You'll learn how to use parameters to access the arguments passed to your function. Finally, you'll learn about exit statuses and return codes.
- Obtain a foundational understanding of functions.
- Learn how to create and use functions in your scripts.
- Learn how to use parameters to access arguments passed to your functions.
This Course is intended for anyone looking to learn more about bash scripting and shell programming.
To get the most out of this Course, you should have some basic knowledge of the command line, but it's not essential.
In this lesson, you'll learn why and when you'll want to use functions. You'll learn how to create functions as well as how to use them. We'll talk about variables and their scope and how that applies to functions. You'll learn how to use parameters to access the arguments passed to your function. Finally, you'll learn about exit statuses and return codes.
Here's a concept in computer programming and application development known as DRY. DRY stands for don't repeat yourself. Functions allow you to write a block of code once and use it many times. Instead of repeating several lines of code each time you need to perform a particular task, simply call the function that contains that code. This helps in reducing the length of your scripts and it also gives you a single place to change, test, troubleshoot and document a given task. This makes your scripts easier to maintain in the long run.
Whenever you need to perform the same action multiple times in a script, that's a sign that you should probably write a function for that action. A function, again, is simply a block of reusable code that performs an action and returns an exit status or return code. A function must be defined before it is called. When you call a function, you can pass data into that function. You can access that data within your function as parameters.
There are two ways to create a function in a shell script. The first way is to explicitly use the keyword function, then follow it by the function's name and then a set of parentheses. Next, you'll use an opening curly brace, the code or commands that follow will be executed when the function is called. To end or close your function, use a closing curly brace. The second way to declare a function is exactly like the first, except that you do not use the keyword function in your declaration. Everything else stays the same. To call or execute the function, simply list its name on a line in the script. After you define a function, it acts as any other command you can use in your shell script.
When calling the function do not use parentheses. You may have seen this syntax and style in other programming language, but that doesn't work in shell scripts. Simply place the name of a function on a line, and it will execute that function. When you run this script, the word hello is displayed on the screen. Be aware that functions can call other functions. In this script, the hello function is declared. Next, the now function is declared.
Finally, the hello function is called. When the hello function is called it prints hello to the screen and then calls the now function, which prints the current time to the screen. You may have caught that the now function was defined after the hello function. And I said that functions had to be declared before they are used. In this example, that is exactly what has happened. Although the hello function calls the now function, and the now function is below it in the script, the now function actually gets read into the script before the hello function is called. So, in the order of execution, it is defined before it's used. If you were to run this script, you would find that it would throw an error stating that now wasn't found. This is because hello gets executed before the now function was declared or read into the script, and this is really the main point of scripting languages. They are not pre-compiled. In some languages, you could define a function anywhere and the compiler would examine all of the source code first and then piece it all together for the final execution of the program. In a script, the commands and components are read from the top to the bottom. It's a best practice to place all of your functions at the top of your script. This ensures that they are all defined before they're used.
Like shell scripts themselves, functions can accept parameters. Also like shell scripts, you can access the values of those passed in parameters using $1, $2, et cetera. You can even access all the parameters passed into the function using $@. The only difference here is that $0 is still the name of the script itself, so you can't access the name of the function using $0, but the good news is that you'll never really wanna do that anyway. To send data to a function, supply the data after the function name. In this example, the hello function is called with one argument, Jason. This means that the contents of $1 inside the hello function are Jason. As you can guess, the output of this script is simply, Hello Jason. This script will loop through each of the parameters passed to the hello function and echo hello followed by the parameter. The output of this script would be three lines. The first line would be Hello Jason, the second line would be Hello Dan, and the third line would be Hello Ryan. By default, all variables are global. This means that the variable and its value can be accessed anywhere in the script, including in any function.
The only small catch is that the variable has to be defined before it can be used. You can't place a variable at the very end of your script and use it at the very top. The contents of the variable will be blank, since it hasn't been given a value yet. This is true for functions as well. If a function uses a global variable, that variable has to be defined before the function is called. If we look at this snippet of a shell script, you'll see that the var GLOBAL_VAR is defined before the function is called. In this case, the value of GLOBAL_VAR can be accessed in the function.
Here's an example of the opposite, since the var GLOBAL_VAR was defined after the function is called, it is not available in the function. If a global variable is defined within a function, it is not available outside that function until the function is called and executed. At the top of the script, the my_function function is declared. It hasn't been executed yet, it's just declared at this point. So if we try to use the variable defined within that function, without calling it first, the value of the variable will be empty. So, in this example, the first echo statement will simply print a blank line.
Next, the my_function function is called. Now a value has been assigned to the variable GLOBAL_VAR. On the echo statement after the function call, it will print one, because that is the value now assigned to GLOBAL_VAR. A local variable is a variable that can only be accessed within the function in which it was declared. Use the local keyword before the variable name, and only used the local keyword the first time the variable is used. Note that the local keyword can only be used inside a function.
It's a best practice to use local variables inside of your functions. However, you'll find plenty of shell scripts that do not adhere to this recommendation. Most of the times it will not cause a problem, as long as you are using unique variable names throughout your script.
Jason is the founder of the Linux Training Academy as well as the author of "Linux for Beginners" and "Command Line Kung Fu." He has over 20 years of professional Linux experience, having worked for industry leaders such as Hewlett-Packard, Xerox, UPS, FireEye, and Amazon.com. Nothing gives him more satisfaction than knowing he has helped thousands of IT professionals level up their careers through his many books and courses.