From the course: Learning Linux Shell Scripting

The basics of functions - Linux Tutorial

From the course: Learning Linux Shell Scripting

Start my 1-month free trial

The basics of functions

- [Instructor] Functions let us avoid duplicating code in our script. We can create a function to hold a single copy of code which we can call from multiple places. Let's take a look at functions. So touch. Func. Dot SH. Do a change mode. 755. And atom. Add our sphang. There are two ways to create a function. The first begins with the word function. So we say function. Hello. And we include parenthesis. And then an opening curly brace. And then we put the function inside of it. And this time we'll just say echo. Hello. The second way to create a function is identical. Except it emits the word function. So now we'll just say goodbye. With the parenthesis. Opening curly brace and then closing curly brace. And in the middle we'll say echo. Goodbye. Now in order to call these, let's just first set up a message where we'll say calling the Hello function. And we say hello. And we'll do another message. Calling the goodbye function. And then we say goodbye. Please note that we don't use parenthesis when we call the function. Like other Linux commands, they are invoked by their name. Add a exit zero. And then control S to save this off. And go to the terminal to test it. And swirly func dot SH. And we get calling the hello function. Hello calling the goodbye function. Goodbye. Also keep in mind that functions must be defined before they can be called. If we move the goodbye function to the bottom of the file. So we're just gonna take this function, do a control X, and then paste it down to the bottom. And do a control S to save it off. And go back to the terminal and invoke the function again. Notice how we get the goodbye command not found. So it can't find that command because it doesn't exist at the time that it is called. So let's go back into atom and fix our script. Restore the goodbye back to the way it was before. Do a control S. And now we know how to use functions in our scripts.

Contents