Shell Scripting Tutorial | Shell Scripting Crash Course | Linux Certification Training | Edureka

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi all this is a partner from Ed Eureka and in this module we are gonna talk all about shell scripting but before we begin let me discuss the outline of the topics I'm going to cover for today so first of all I'm gonna give you guys a little brief on Linux why do we need it what exactly is Linux a little bit about the kernel in the shell then we're gonna talk about the command line essentials as this is a scripting video most of what you're gonna look at is going to be the CLI then we're gonna start with shell scripting basics followed by how to use variable some special variables and how could you implement them then we have basic operators followed by shell loops and shell functions and finally we are going to look at a few use cases in a small-scale value to see how shell script is implied in daily lives of people so without any further ado let's get started so first of all let me introduce you to this thing called Linux now firstly why do we need Linux now there are a couple of reasons why people into scripting as a background would prefer Linux over any other OS firstly it's an open source operating system which basically means the source code is available to everybody which also means that when you use the Linux OS you can customize it according to the nature of your work which brings me to the second point which is access to the source code as I had mentioned the source code is present to everybody you can make tweaks in the code which suits your needs the Third Point Linux is highly secure it is so because it's easy to identify bugs and fix them whereas when we are talking about a widely distributed OS like Windows which has a large user base it becomes a target for developers of viruses and malware and finally you shall notice later in this module that if we remove something from the Linux OS it gets deleted forever unlike your Windows OS Varon it gets saved in your recycle bin during your entire OS and slowing it down which is why Linux runs faster and is meant for faster systems now that we know why do we need Linux let's look at what is Linux now Linux is a UNIX clone which has been written from scratch by Linus Torvalds it is an open source and community developed operating system for which it is capable of handling activities from multiple users at the same time now we cannot just talk about Linux and not talk about the kernel now the computer programs that allocate the system resources and coordinate all the details of the computer's internals is called the kernel so basically the kernel is like the heart of the operating system it interacts with the hardware and most of the tasks like memory management - the duelling and file management is done by the kernel now users communicate with the OS through a small program called the shell which we shall be elaborating upon later now this is one of the very interesting applications of kernel which is the Apple's iOS or the Mac OS now what Apple did as a company was that it put on a pretty skin on your basic Linux kernel to make an OS of its own now Apple uses its own signature operating system xnu since 2001 which a lot of people do not know has been derived from the basic UNIX kernel back then it was known as the OS X which later became the X in you now let's move on to our command-line essentials for that I am going to take you to the terminal now because this is a scripting video if you're gonna spend a lot of time on the command-line interface now this is important because it saves you a ton of time you can't just keep switching from CLI to GUI in any real life given scenario so I am using Center West 7 the Fedora version and I'm running it on a virtual machine so first of all what I'm going to do is I'm going to increase the size of the text a little bit I think this should be fine and then let's start with making a list of all the commands that we shall be acquainting ourselves with for that I'm going to open the Nano editor and I'm gonna name this CLI essentials all right now nano editor is basically a text editor like any other I could have used whim instead of it but I like the Nano editor because it gives you a bunch of options in the bottom and it's just easier to use so let's start with our list so we have our basics which are CD which means change directory PWD which will show you the directory then we have LS or list then we have the next segment which is the copy the move and the remove they pretty much do what the name suggests the copy move and remove respectively then you have echo which is like Linux is version of print you have cat or concatenate then you have less which by definition both of them should sound pretty similar but in a bit I'll tell you why they are different then we have grep we have mkdir which basically helps you make a directory and then we have touch which basically helps you make files pretty quickly then we have change mode which is also pretty significant I'll tell you in a bit why and then finally we have man plus help which is basically like a manual then if I have to save this I just have to write out so ctrl o then it will ask you whether this is the name you want to save this with and hit enter and then it tells us that we have written 14 lines now all I want to do is exit this so ctrl X and here we are back on our basic terminal so let's start change directory right now as you can see we are at Eddie Rica our current working directory so CD slash home as simple as that now we are at home then we can do a CD and back to Eddie Ricker then we have PWD which will show you your current working directory as you can see it shows home slash at Eureka it's the path of our current working directory then we have LS it shows all these files that are there in our current working directory not just that you can also write LS and specify a path name so then it will give you the list of objects that is there in that particular file so at home you have these two files called at Eureka and by grunt now what else can we do with LS we can go ahead and look at the flags that are available for that all you have to do is - - help now that works universally through all distributions of Linux now this may look like a lot of text now but if you go up you would realize that there are flags and that descriptions given on the left and right respectively you have your - a which means do not ignore entry is starting with your dot then you have capital a which means almost all and then it has its description right here what I'm more interested in comes all the way down here which is your L flag or the long listing format let's use that and see now I had done LS before now if I go on and do LS - L it's basically going to show me all my objects the same as LS but is going to give me more information about these objects like the date and time at which this object was created who is the user the user group and on the extreme left if you see it basically shows you the permissions which I'm going to talk a little more about later in this segment right now all I want to tell you is are here stands for read W for write and X for execute so when you see our W X written on the left it means your user can read write and execute that particular file okay with that let's clear this all right let's move on to our next set of command line essential commands so what else did we have we had copy so for popping all you have to do is type CP type the name of your file and then put in a destination path in this case I've put in pictures which is there in the add Eureka directory and with that it is copied now let's see if it is actually present in pictures so again let me just use the list command and you can see CLI essentials is right here now let's see how to use the Move command for this I am going to be moving to this pictures directory Oh first up let's just see what other file can we make the move - all right we have downloads we have project public all right so first let's move into pictures so now I'm at pictures what I'm gonna do is I'm going to move CLI essentials to let's say I'm going to move it to public okay now once the move is done if we see public let's list our public you see there is just one file which our CLI essentials but then if I go back and check pictures there is no CLI essentials file which basically means what movin did was it removed the file from the pictures directory and put it in public now let's remove that file from public with which we can also cover the RM command so let's move into public now as you can see we are at public let me clear this I'll keep clearing the screen for which you can just type clear or use ctrl L and let me remove CLI essentials now if I do an LS you see there is nothing there in the public directory so with that let me move back to Ed you record the original working directory I was in let's see what are the commands that we were using okay we've done CD PWD LS CP MV + RM next we have echo now as I had mentioned echo is like the print command in here so if I'm gonna say echo hello world like we haven't used this phrase a million times already but I'm gonna stick to the cliche and I'm gonna still type that it prints out hello world surprise surprise and as you might have seen what I previously did which was using the cat command I'm going to do it again basically what the cat command does is it concatenates your text file to this terminal of yours so what is there in that particular text file CLI essentials I can see it printed right here now how is that different from the LES command now if I did the same thing with less it will also show you the contents of your text file but it will open it on a brand new separate window and just override the previous window you were working on now this is a much neater way and it helps you from not cluttering the window that you're currently working on so that was all about cat and less for grep let's move back into our original window for that all you can do is press Q and then you're back here so the next command you're gonna do is grep basically what it's gonna do is it's gonna grab the data from a certain file or a command that you are trying to pursue so you guys might remember I just used the MV or the move command so what I'm gonna do is MV and go to help because if you remember your - - help would basically bring out this entire manual of the flags that are there for MV then we're gonna pipe and we'll do this thing called grep type out verbose so basically what I'm trying to find out is is the verbose flag available for your moose command or not so as you can see your - V or the verbose flag basically what it does is it explains what is being done while you move it so if you use the - V flag with your move command it's going to show you basically where you're moving your file and if suppose you're using a big file suppose a 12 or 20 GB file it's going to show you when it starts and when it is finished with that let's move on and let's see what else so we finished catless grep next we have touch and mkdir now touch will be easy to show it is basically going to help you create a few files quickly in the current working directory that you're working on so file one dot txt then we have five two dot txt and let's take five three dot txt not very original but just have to show you how it works and if I do an LS you can see you have file one dot txt file two dot txt and file three dot txt right here next we have mkdir which basically helps you make a directory in your current working directory if I just type files and then I'll do this LS again you see we have created a directory which it will show you in blue and we have created files then we have CH m OD or change mode now this basically helps you play with or alter the permissions that are associated with if I now let me give you an example by running a script so what I'm gonna do is I'll open script so basically what I'm gonna do is that I'm gonna write a little script now this is a no means me rushing into the next segment that one is separate this is just for me so I can demonstrate how you use chmod so I'm gonna go with shebang line I'm gonna just go with hello world or hello Lana because we have used hello world a lot so I'm going to write out of this control oh and then you're gonna move out of here now let me clear this out and let's try to run that particular script so this is how you run it you go dot slash and then test dot Sh and as you see it basically shows you permission denied now one thing you should remember is any script that you've just written isn't executable from the get-go mostly you only have permissions to read it now to change that condition we have something called chmod so when you go ahead and type chmod and then your plus R or plus W or plus X it means you're basically adding to whatever permission that there is a permission to execute that particular file so with that plus X now let's try running this and as you can see hello learner so what I could have done instead of the plus X is I could have done this 777 and then test which would have meant the same thing but there is a difference from just adding a permission to the user and using the chmod this way for that let me open another nano editor called permissions so I can explain it to you further now remember how I had said when we were using long lists or the extension - L - LS that on the leftmost column what you could see were the permissions associated with a certain file now chmod basically helps you alter that now if you might have noticed the permissions were displayed in the following fashion suppose ABC and then ABC and then one more ABC and then the file name and then the date and then whatever basically there are three aspects to it the first one being the user or you second one being the use group and finally there's a thing for everybody else so when you basically type chmod and followed by three numbers you're basically specifying the user the group and others and then the file name which is the basic syntax of chmod now how does this work now these numbers can be anything from zero to seven and all those numbers mean something now let's start with 0 we have 0 which is equal to 0 which basically means nobody gets any permission then we have 1 which basically means only execute then we have 2 which means you can only write then you have 3 which is basically the sum of 2 plus 1 which means you can write and execute then we have 4 which is read then be a 5 which is essentially 4 plus 1 which as you all might have guessed means read and execute then we have six which is read and write and finally you have seven which is 4 plus 2 plus 1 which means all 3 permissions read write and execute not going to be saving this so when you type something such as chmod 777 and a certain file name your first 7 basically means your user has the permission to read write and execute your second 7 means your user group also has the permission to read write and execute the file and so does everybody else which you can see through the third 7 with that I am closing this so control X then I'm not saving it and then finally I have man plus help which is basically your general commands manual you can see the names of all your general commands you can see your Bosch bulletin commands it's basically like your guidebook before scripting you can press H and it will open to a summary of commands and then you can press Q when you are done again q now let me head back to my presentation for a little more on CLI now basically before closing this segment I'm going to talk a little bit about CLI and how it compares to GUI supposedly the first point must be pretty clear CLI actually stands for command line interface so it basically means it's a text-based interface now the GUI or the graphical user interface is a visual based interface pretty clearly it features the use of graphic images including windows icons and menus even if it does that it does require a mouse which is the most common way to navigate through a GUI which brings me to my next point icons are easy to use because of the visual representation most people can learn and use GUI much faster and much easier but once you get used to the command line I don't personally think it is that of as well but for a beginner yes GUI can prove to be pretty optimum but there is also a downside a GUI is OS is slower because everything you remove does not get permanently removed from the system it is going to stay there as a copy of the file and going to clutter your space and reduce the speed of your whole system which is very CLI wins as it has a faster OS which also brings me to my final point command line interface gives you way more control than your GUI with the CLI users have all the control over a file system and their operating systems and the tasks become really simple you can create a script that contains a few lines of command and it will do the work for you although your graphical user interface can create shortcuts they do not readily support scripting or automation so for common tasks a user must repeat each action within the GUI manually now nothing is better than the other it's a personal choice for everybody but for scripting obviously a command-line interface is most optimum it helps you do things at scale it helps you when you need to script or automate something you need greater control over systems or functions and it helps you with less memory usage would that let's move want to the shell script basics so the most logical question obviously is what is a shell as I had mentioned earlier users communicate with the kernel through a program known as a shell a shell is basically a command-line interpreter and basically what it does is that it processes your requests when you type in a command at your terminal the shell interprets the command and calls the program that you want the shell use a standard syntax for all commands so basically what it does is that it translates commands entered by the user and converts them into a language that is understood by the kernel from the shell the direct derivative is the shell script now the basic concept of the shell script is that there will be a list of commands which are listed in the order of execution a good shell script will have comments preceded by the hash sign now it is not important for you to have hash signed certain comments for your script to be executed it is only a good practice to have your steps hashed out so somebody else reading your script can understand what you want to do with it now there are several different types of shells which can be broadly classified into two types first you have the classic shell which is the bourne shell a derivative which came later with the c shell now each of these types have their own subtypes a few examples of the bourne shell are the basic bon shell the conch shell the bourne-again shell or the bash and the POSIX ship in sea shell certain examples are your basic sea shell your 10x sea shell and the sea shell which has been picking up popularity in the past few years now to understand how this works let me move on to our terminal now what I'll be doing is I'll be dividing the screen at two parts on my left I'll have my Nano editor and on my right I shall be having your basic terminal where you can see your commands being executed so kindly be patient okay so let's start with some basic shell scripting now shell scripts have several required constructs that tell the shell environment what to do and when to of course Machel scripts are more complex than the one I'm going to show you the shell is after all a real programming language complete with variables control structures so on and so forth no matter how complicated a script gets it still is just a list of commands executed sequentially so here I'm going to open up my Nano editor and I'm gonna put up let's say example 1 and s H now notice the extension SH this is my extension because I'm using the basic bon shell or the share so I'll start with the shebang line and it is nothing but the absolute path to the interpreter of your shell so it has this hash and this bank or the exclamatory followed by the full path to your interpreter now all scripts under linux execute using the interpreter specified on this first line so this could be SH or bon shell bash or your case as your Z research so on and so forth now like we had given the advice of hashing out comments let me just put on a few comments make this look good okay and then I'm gonna put up try and print this very simple print such as what is your name and then I am going to read whatever you enter and then I am going to print that out you're gonna allocate whatever we read into this variable called person and then we are going to call that variable using the dollar sign so hello whatever person as I mentioned before your controlled oh right out and then give an exit this now this is to remind you one more time that every file which has just been made is not executable so if I try to execute it now it would tell me that permission is denied this is just a recap of what I had done say two minutes ago so we're gonna change the mood and I'm going to do this when I'm executing to any script at all try and execute it now it's gonna ask me what is your name at Eureka employee and then it's gonna greet me saying hello at Eureka employee and that is the most basic of the shell scripting that you can do as we move further I'm going to keep bringing you back here I'm firm believer in practicing what we are learning in theory would that let's go on and see what we have next in this module so the next segment is about using variables so what is the a variable most people might be aware of this term but for those who are not I'm going to explain it down to the scratch for all of you now variable is nothing more than a pointer to the actual data it's nothing more nothing less the shell enables you to create a sign and delete variables so basically what it is is that a variable is a character string to which we assign a value the value assigned could be a number text file name device or any other type of data the shell enables you to create assign and delete variables which may contain numbers texts file names devices or any other kind of data variables are of three kinds in the shell you have your local variables which as the name suggests is the variable that is present within the current instance of the shell it is not available to programs that are started by the shell and they are set at the command prompt then you have your environmental variable an environmental variable is available to any child process of the shell now some programs need the environmental variables in order to function correctly usually a shell script defines only those environmental variables that are needed by the programs that runs and finally we have the shell variables which can be compared to the global variable if you're into any other kind of programming a shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly now some of these variables are environment variables while others are local variables it can be any of these now to see how we can implement these variables we are going to move on to the shell but before that let's see specifically what we are going to look at so first of all we are going to learn how to define variables how to access the values then you're going to see a little bit on read-only variables and unsetting variables then we have special variables you can see how you can work with them we have command-line arguments we have special parameters and the exit status now to see how all of these things work let's move on to our terminal so again I'm going to create another nano file called variable dot SH now defining variables now any variable that you are going to define should be along the lines of this you have your variable name and then you have your equal sign and your variable value now if you have done any sort of coding or programming before you would know this is basically how you allot a value to a variable throughout all different platforms now the thing you have to notice is that ensure scripting it's very particular about the syntax so no spaces on either side of your equal to sign in that case it is not going to execute and it's going to throw an error at you so let's take something simple so your name equals this now this example defines the variable name and assigns the value at Eureka employed to it variables of this type are called scalar variables now a scalar variable basically means that it can only hold one value at a time so let's turn this into a shell script first so I'm going to go up and put in my shebang line and then I have my name and then we're just going to call that particular variable pretty simple and we've done it before so then control o here again we have to give it permissions and then when we executed it prints out what we had asked for it to print out okay let's see what happens when I use the read-only command and then I try to change the value of the variable suppose I put in my own name into it I'm gonna go ctrl o and okay basically is going to throw an error at me saying that the variable name is a read only variable so I cannot change the value of the variable once I put read-only in front of it now that was all about read-only variables now let's move on to see what else can we do with this now there is also something called unsetting variables now unsetting or deleting a variable directs the shell to remove the variable from the list of variable that it tracks you'll see in a moment what I mean so I did this and then instead of read-only I'm going to put unset and then I'm gonna call my variable same old same old and now we are going to try and call this as you can see nothing so basically what it did was it took the variable out of the list of other variables that is what unset does now let's clean this out and we can look at special variables okay so now let's discuss a little bit about special variables so in the previous segment you understood how to define a variable how to read only and unset available now these variables are reserved for specific functions and hence they are called special variables now they're usually preceded by a dollar sign and these are the special variables that we are going to see you have your dollar zero which is the filename of the script then you have your dollar any number one to nine now these variables correspond to the arguments with which a script was invoked here you can pick any n number which will be a positive decimal number corresponding to the position of the argument you shall understand when I demonstrate this further in this segment then you have your dollar hash sign now this will basically return the number of arguments applied to a script then you have your dollar and asterik so this will return you all the arguments that are double quoted which again you shall see when I demonstrate this now this will give you all the arguments that are individually double quoted that is the only difference between the dollar asterik and the dollar at the rate sign then you have this which is the exit status of the last command that you have executed and finally you have the dollar dollar which will give you the process number of the current shell for the shell script now this is also the process ID under which it has been executed now let me try to scrip something with which I can depict not all but at least most of these special variables so let's just put on echo big dollar zero then we go ahead select it and then copy it a bunch of times you okay so let's go ahead and execute this so now that we have learnt about all of these special variables let's implement them using command-line arguments now command line arguments as you can see on your left are these dollar one two three to nine they're actually positional parameters with dollar zero pointing to the actual command following which you dollar one and your dollar two are the arguments to that particular command if you see the script on your left this is how it will run so first we are going to change the mode then we are going to run it and pass a parameter here so if I pass an array car employee or after that too many times so and you recall learner and enter it shows you the file name dollar zero your parameter number one which is a eureka your second parameter the quoted values and the number of parameters all of which are returned to us by our special variables now as you might have noticed Yordano at the root sign and your dollar star sign return pretty much the same thing these are the special parameters that allow accessing all the command line and arguments at once which in our case is ad you're a car learner both of these arguments so both of them actually act pretty much the same unless they are enclosed in double quotes now let me show you how if I run the same thing but I put them in double quotes you can see both of them again give the same value but if I put them in individual quotes it will treat them as two separate parameters and will give you two separate values whereas in the first one it will quote your number of parameters as one it will consider it one single string now let me try and demonstrate it using another shell scrip how is it different this does not make a lot of sense to most of you right now so let's just hope the next thing makes it better so I'll run a little for loop here which again we are going to touch up on later but for now let me just do this to demonstrate how this works now let me put this in perspective so what I'm going to do is I'm going to run this entire sentence and Eureka wishes you happy learning and you see what just happened right what your special parameter did here is that it took this entire list and separated it into separate arguments and that is what these two special parameters do now once you're done with it you can always use the exit status so what I'm going to do now finally is I am going to go and implement the exit status and it is going to return a value of zero now this is basically the exit status of the previous command it would have given you a 1 if your previous command was unsuccessful since your command was successful and gave you a zero so the exit status is basically a numerical value returned by every command upon its completion as a rule most command return and exit status of zero if successful and one if unsuccessful now some commands also return additional exit statuses for particular reasons for example a few commands will differentiate between kinds of errors and will return various exit statuses depending on the specific type of failure with that we've come to the end of this segment let me go back to my presentation next let's take a look at our basic operators now they're various operators supported by each shell I'm not going to take a lot of time with this segment we will discuss about the default shell in this segment and we're going to discuss the following operators we have the arithmetic operators relational operators boolean string and file test operators so this is the first table and these are your arithmetic operators you have addition subtraction multiplication division modulus assignment equality and not equality is very important to understand that all these conditional expressions should be inside of square braces put spaces around them now all the arithmetic calculations are done using long integers next we have relational operators now the bond shell supports these relational operators that are specific to the numeric value now these operators do not work for string values unless their value is numeric we have again the equal operand not equal to greater than less than greater than equal to or less than equal to then we have the boolean operators which are just three there is the logical negotiation logical or and logically and and finally we have the string operators which are equals not equals check if operand is zero not zero and check if string is empty and finally we have the file test operators now we have a few operators that can be used to test various properties associated to a UNIX file now assume a variable Phi holds an existing name of the size hundred bytes and has to read write and execute permission on so you have your - B which checks if the file is a block special file then you have I can see good checks if a file is a cat a special file if the file is a directory which is - D - f is if a file is an ordinary file as opposed to a directory or a special file then you have - G good checks of the file has its set group ID - K which has its sticky bits set - P which is a named pipe - T good checks if it's associated with the terminal I think you has it set user ID R is readable W is writable and X is executable which we had discussed before then you have s over the size greater than 0 and E if the file exists now these are specific to the bond shell there are other operators that are available in the c-shell types but you shall find a lot of content surrounding that it's not really crucial to discuss that in this module so let's move on next we have shell loops in this segment we're going to discuss shell loops in Linux a loop is basically a very powerful programming tool that enables you to execute a set of commands repeatedly here we shall discuss the while loop the for loop until loop the nested loops and loop control which will include the infinite loop and how to get out of it with break and continue commands for that again as most of you might have correctly guessed let me head back to the terminal so first let's discuss the for loop so the for loop operates on lists of items it repeats a set of commands for every item in the list so let me open the Nano editor let's see let's call it edit all right so basically this is how the syntax of your for loop goes for your certain variable in say your word one word two so on and so forth till your word n then you have a do statement whatever you want your for loop to do and then done and this is basically how your for loop works so here I'll give you a simple example of how the for loop works it's basically going to span through a given set of numbers set 0 to 9 and upon execution it should print all those numbers it's basically printing out this variable for all the variables that are there in the set it's pretty simple so again chmod and then and there we go now what if you had to do the same thing using another way we have for you the while loop let's get out of here let's open this and see how the while loop is different from the for loop now the while loop what it does is that it enables you to execute a set of commands repeatedly until some condition occurs so it is usually used when you need to manipulate the value of a variable repeatedly the syntax of awhile come and look something like this so you have a while and then you have a command or condition if you will then you do and then there's this statement what you want to be done and then done I'm going to demonstrate the same example using the while loop now this is basically going to do what we did with the for-loop but using the while loop we start with assigning a value to a which is our variable now we say while a is less than 10 it's going to print a and then increase the value of a to a plus 1 that's all that is there inside the loop now let's try executing this again I'm going to change the permissions and it prints the same exact thing here the shell command is evaluated if the resulting value is true so as long as a is less than 10 it will keep printing a and adding 1 to it once it reaches 10 your while loop breaks and you come out of the loop each time the loop executes the variable a is checked let's try doing this one more time using the anti loop let me clear this out now the while loop is perfect for a situation where you need to execute a set of commands while some condition is true sometimes you need to execute a set of commands until a condition is true and that is where you use the --until command I'm gonna go back here and you'll notice that the structure of Anton command is pretty similar to that of your while again you have your until statement then the command or the condition then you have your loop beginning whatever you want to happen in the loop and then done so once the shell command is evaluated if the resulting value is false the given statement is then executed if the command is true then no statement will be executed and the program jumps to the next line after the done statement so again because I'm lazy I am going to do the exact same thing as I did twice before but this time using the antal command same thing here instead of while it's until so until your E is not less than 0 it's going to keep printing a and then incrementing the value of e so even if what gets printed is the same you know for a fact that how the procedure was gone about who is different when you use the Y command new statement is executed while your condition is true but when you use the until command your statement keeps executing until your condition is true with that let me clean this out and then we shall move to nested loops let me get out of here okay no next let's talk a little bit about the nesting of loops now all the loops support nesting concept in Linux which means you can basically put one loop inside another similar or different loop this nesting can go on up to unlimited number of times based on what you require now let me give you an example of nesting using the while loop so remember the simple while loop that you ran which went from zero to nine what we're going to do is basically we're just going to add another while inside the previous one so Nana okay remember till here it's pretty much the same as the previous one that is your first loop inside we are going to assign the value of A to B and why your B remains greater than zero it's now going to go to a new line which is this n flag print B and then increment B once it comes out of the loop it's going to increment a and so on and so forth let me show you what this looks like now the result here is not very important but what you need to understand is how the basic structure of the loop is and how it works so again like you can see a starts with zero now while a is less than 10 0 being less than 10 a is assigned to B now why B is greater than equal to 0 which now B is it is 0 it's going to go to a new line and print B it printed 0 then it's going to increment the value of B and turn it into 1 and now once B is incremented it gets out of that loop followed by the increment of a which now a becomes a plus 1 that is 1 and it keeps going on and on and on and on till finally your a is no longer less than 10 so with that let's move on to our next topic which is of loop control here we are going to discuss some very important concepts but before I introduce the concept of loop control first we need to understand what infinite loop is select mean create an infinite loop so let's start with a equals suppose 10 and let's go singing as long as E is greater than 0 start your loop and you're gonna print E and then we are going to increment the value of a and then done control Oh you and now what this is going to do is it's just going to go on and on and on and on and on because it will go on until a is greater than zero and it's always going to be greater than zero so let me just put a stop to it this by using control-c I can put a for stop to it now you can also do that using something known as the break statement and the break statement is used to terminate the execution of an entire loop after completing the execution of all the lines of code up to the break statement now let's see how that works so I am going to exit this and now this is a simple example which shows that the loop will terminate as soon as it becomes equal to five so let's go ahead and you go and one two three four five now another statement associated to it is the continue statement which is similar to the break statement except that it causes the current iteration of the loop to exit rather than the entire loop so this statement is useful when an error has occurred but you want to try to execute the next iteration of the loop let's look at one of those so basically what you see in the script is that this loop makes use of the continue statement to return from this particular statement to the next one which is the found odd number statement you so if we try to run it you will receive this result found an odd number even odd even odd even odd it's basically very similar to the break command except for the fact that your break Amon will exit the entire loop while the continue statement will only exit the current iteration on your left you see this little script where we're trying to see this numbers that we have put in 1 2 7 which of them are even and which of them are odd now what you see here is that the script uses the continue command to exit from this particular statement to this particular statement so if I tried to run this it keeps exiting this to produce this even number statement with that we come to the end of shell loops let's go back to the presentation to see what we have next so in this segment we will discuss in detail about functions in the chef now basically what functions enable you to do is to break down the overall functionality of a script into smaller more logical subsections which can be then called upon to perform their individual tasks whenever needed so in this segment we are going to talk about creating functions passing parameters returning values nested functions and calling from prompt so here we are at our terminal let's again open our Nano editor so to declare a function is very simple what you will have to do is type your function name and then go ahead with your list of commands and then close the bracket this is all that you have to do now let's start with this very basic function dot with the shebang again not to be confused with the shebang in the pop culture that we use so what we're gonna do first is that we're gonna define function so again this is my function name it's going to be hello and then I am going to just print hello learner nothing very complicated and then all I have to do is just invoke my function or call my function whatever it is so hello then I'm gonna save it and here it basically called that function and that's how simple that is now using functions to perform repetitive tasks is an excellent way to create code reuse this is an important part of modern object-oriented programming principles now shell functions are similar to subroutines procedures and functions that are present in your other software and hardware coding languages the idea here is to break down a big program into smaller more logical subsections which can then be called whenever they need it now you can define a function that will accept parameters while calling the function now these parameters can be represented by dollar one and dollar two as we had passed parameters early on if you remember now here if I make some minor changes to my function I think I can make it accept parameters so hello and I can put two different parameters and then what I can do is I can put those parameters right here let's say I put two names let's say I'll put freon car Chopra because you're not pretty international let's just keep it that way and that is what it called basically these two parameters were captured and printed in this function what you can also do is return values from functions if you execute the exit command from inside a function its effect does not only to terminate execution of the function but also the shell program that called the function if you instead want to just terminate the execution of the function there is a way to come out of the define function now based on the situation you can return any value of the function using the return command so again what we can do is make some changes here let me return this another thing I'm going to do is capture the Sten value that has been returned from my previous command all right so what I'm gonna do is I'm gonna print this out by echo and then value is so I'm own - with the skill you so here as you can see the parameters that we had passed and the value that has been returned now one of the more interesting features of functions is that they can call themselves and also other functions a function that calls itself is known as the recursive function as most of you might know now I'll also give you an example demonstrating the nesting of two functions so let me just clear this out I could open a new nano editor but let's just say I am very lazy so you okay now let's execute this basically we have a function number two inside the function number one function is saying alpha online over and then calling number two and number two here is printing beta online and then we are calling the function number one which is our super set if you may in the function so if we execute this we get the first one alpha online over and beta online I clearly watch a lot of movies as well and now you can put on definitions for more commonly used functions inside your profile and these functions will be available whenever you log in and you can use them at the command prompt alternatively you can also group the definitions in a file and then execute the file in the current shell with that I come to the end of the segment as well now we are going to move on to some used cases on a small scale of course to see how shell scripting is used on a broader scale on a day to day basis so I am going to clear this and I am going to clear this as well so let's run a few simple scripts to scan and monitor network using the combination of your shell script and your ping command obviously these scripts are no match to a full monitoring dedicated software like Nagios but they could be useful for a small home brand networks we're implementing sophisticated monitoring systems can become an overhead let's look at something simple first okay let's look at a scan so your dot slash okay so let me just show you the code for this so right now we are going to run a few simple scripts to scan and monitor the network using a combination of Bashan ping now this is a disclaimer here these scripts are no match for a full monitoring dedicated software something like your Nagios but they could be very useful for small home brand networks we're implementing sophisticated monitoring systems can become an overhead so let's start with something simple like scanning a network so this is the code in this script what we are going to do is we are going to scan the network for hosts that are attached to an IP address and the script will print the message nodes with IP so if your IP address is up then your ping command was successful feel free to modify the script to scan your hosts range whenever you try it so as you can see it starts with your basic shebang line then we are using our ping and we are basically checking for the exit status for being 0 now if your exit status is equal to 0 then it will print that your IP address is up pretty simple if we go deeper into it now we are going to run this loop for IP addresses from 1 to 255 in the subnet one ninety two dot one sixty eight dot two basically what's going to do is it's going to ping these many systems and check if they are up and then disown them all right let's try running the script now as you can see these many systems are up in this particular subnet we have a bunch of different ones one of them should be mine this one seems like it's mine and so on and so forth all right let's move on to our next script basically what I did just now is I for stop this script alright okay now what we're going to do is we will try to send the email to my email address when the pink cannot reach its destination which probably means the host is down so system admins can execute this in a script regularly with the use of a cron should EULA now this script uses ping command to ping the host or IP that is supplied to an argument and in case that destination is unreachable a mail command will be used to notify the system administration about this event so let's look at this so cat all right now this is what the script looks like also a pretty small code again it starts with the shebang line and it runs a for loop now here you can see there is a special variable used which is your dollar Act which basically means that all the arguments are individually double quoted so inside this for loop basically we are trying to ping all the parameters that are passed and if the set parameter is not equal to zero then we are going to get email to this particular email address that the host is down all right so previously we had checked for an entire subnet that is why we didn't have to pass on any arguments but here since we are not running it for an entire subnet we are going to try it on on some trusty websites so before I call in this code I would like to show you that this is what my Gmail tab looks like there's nothing in my inbox currently so what I'm expecting is that when I pass on an argument which is not supposed to be up I'm supposed to be getting email in my Gmail right so let's run this let's put in google.com because we know it's always running so let's put yahoo.com let's put in an imaginary IP which I'm sure let's hope this does not exist let's put on one more for safety okay now we've put in four we know for a fact that google.com is always up so has yahoo.com now we will have to check which of these two IP addresses snot up now let me open my Gmail and check and as you can see I have two new messages and if you open the mail you can see the message that we had put in as input all right now that we've done these two things let us try an extended version of the same thing now I for stopped this particular script from running because it will go on and on and on and on now what we're going to do is that we're going to create a monitoring log so the last example I'm going to show you here is a modified version of the previous two examples now this example that I'm going to show you is a modified version of what I just showed you when the mail is not configured on the system the script will create a log file now the core of the script is wrapped into this endless while loop which is set to execute ping and check every minute feel free to modify the script according to your own needs and you can also go ahead and remove the endless while loop when you intend to use the script with a cron Shin Yool all right so let's see what our script looks like so this is our script let me break it down for you a little bit so first of all I have created the slob file which is going to save if your host is up or down in a temporary log file it basically is a directory then I have create another variable called seconds so this script is going to run every 60 seconds to check which host is up the email is my email which I had shown you previously then the for loop begins now this is very similar to the previous code that we had just run this is the same part and here we have an infinite loop which is basically what we're gonna run to check if a host is up so we are gonna ping the various arguments that we are going to pass and if the said argument is not equal to zero then the status gets logged into our monitored log and if the status is down then again like our previous code we get a mail that our host is down else if the host is up you just ping ok the host is up and there is no mail now the reason why I'm not sending a mail when the host is up if suppose somebody uses this code to check a subnet of a lot of systems you do not want to spam yourself with a bunch of different mail saying the horse is up that is not important we want to know when a host is down and then this if condition closes within f5 and your argument being up is also sent to the log and then we have sleep for the seconds variable which we have put up as 60 seconds so as I had mentioned the script is going to run every 60 seconds so let's run this I'm gonna check for google.com and this imaginary IP address which as we had previously seen is not up and then let's put in yahoo.com and Yahoo 1 2 3 . kombucha I'm hoping is not an actual website let's put in this two point two point two now let's run the script this might take some time so kindly be patient let the script run so while it runs let me explain this to you as you can see the core of the script is wrapped into an endless loop which is set to execute ping check every 60 seconds whenever you try the script feel free to modify it according to your needs and if you intend to use the script with a crunchy doula feel free to remove this endless loop because that's what a crunchy ruler will do on its own ok so I think that's enough time let me just stop this and as you can see I have already gotten the new messages here again as you can see this does not exist this does not exist the hosts are down so our ping has failed and so we've gotten these mails now what else can we do with it let's try to understand a script to create a network back up sort of a file so let's see what that code looks like so for this code I'll have to go back to route let's check if our file is here and it is so let me show you the code for creating a backup of a file in your network to your local system all right now this is what your code should look like so first of all you're going to mount the shared directory which basically means you're not creating a copy of the directory but if you make any changes in your local file it will be reflected in your shared file and vice versa so CIFS is basically used for sharing your window file this is the path of your shared file and this is the path to the local directory where you're going to create your backup we've had a user name at Eureka and we've set the password at Eureka that is what - OH does so again we've mentioned what are we going to backup this is the file that we are going to backup and this is our destination now basically we're going to create a backup and save it in the name of the day so for example today is Thursday so if I create this backup today then it's going to be saved in a folder called Thursday our host name is localhost and so our archive file is going to be localhost - the name of the day which is Thursday dot tgz is basically your tar ball file extension and then we've put in a print of the start status message which is basically supposed to inform us that we have started creating the backup what czf does here is it basically creates a zip file because we are obviously going to import files into the local system and in the end it is going to show us a message called backup finished and finally we are going to unmount our shared directory so first let me show you the file that I am trying to back up over here so now that we know what the code looks like let's give it a run so dot slash so as of now it's creating a backup and remember I had told you this is how it's going to name it localhost unscored Thursday dot T GC localhost being our host name and Thursday being today's day and it's also showing us that these are the folders that are present in our backup directory so how are we going to see it let's first head on home change directory to add Eureka you so let me clear the screen and let me head on home you so here I'm home at at Eureka and this is the list of everything that is there so as you can see there is a file created here called backup and now we're gonna extract the files and see if the code that we've run has actually worked or not so let me go to that file and so now I'm going to unzip the file and see if actually now let's go in here and check if we actually have our files in or not let's go and unzip this file you and here are all the files that are present in that particular folder we have a bunch of PNG images as you can see now if the same thing I had to show you in GUI I'll go to home and this is my backup file this is you and these are the PNG images that have been imported into this folder with that I come to the end of my demo thank you and have a great day I hope you have enjoyed listening to this video please be kind enough to like it and you can comment any of your doubts and queries and we will reply them at the earliest do look out for more videos in our playlist and subscribe to any rekha channel to learn more happy learning
Info
Channel: edureka!
Views: 656,335
Rating: undefined out of 5
Keywords: yt:cc=on, shell scripting tutorial, shell scripting, shell scripting tutorial for beginners, shell scripting tutorial advanced, shell scripting advanced tutorial, shell scripting and bash scripting, linux shell scripting tutorial, shell scripting basics, shell scripting complete tutorial, shell scripting crash course, shell scripting course, shell scripting tutorial in linux, shell scripting projects, shell scripting programs, bash script, linux certification training, edureka
Id: GtovwKDemnI
Channel Id: undefined
Length: 74min 31sec (4471 seconds)
Published: Thu Apr 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.