Shell Scripting Tutorial | Linux Tutorial | Shell Scripting Training | Intellipaat

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hey guys, welcome to this session on shell scripting by Intellipaat. The urge of of shell scripting is increasing by the day. Shell scripting languages can be used for multiple purposes, such as automating repetitive tasks, backup and maintenance of databases, and running Corn jobs. So, today, we have come up with a comprehensive tutorial on shell scripting. So before we start with this session, do like this video and subscribe to our channel so that you never miss out on any of the upcoming videos. Let's go through the agenda. We'll start off by understanding what is a Linux shell, and then we'll write our first shell script. After that, we'll learn how to assign variables, and we'll look out on some of the examples of shell scripting. After that, we'll work with different loops, and finally, there would be a quiz to recap whatever you have learned in today's session. So, put down your answers in the comment box so as to check if you have answered correctly. Also, if you have any queries, feel free to write it down in the comment section, and we'd love to help you out. Without any further delay let's start off with this session. First of all, here we talk about what Linux shells are. You might have known by now what a Linux shell is. As I said, Linux has a kernel which is the core, and that kernel talks to the hardware, but the kernel doesn't understand the language we users use. So that's why, there's a shell. Shell is the interpreter between the kernel and the user. So, the user types in commands for whatever he needs and the shell interprets them and then sends it to the kernel for execution. So, this is how Linux system works. The shell is an environment in which we can run our commands, programs, and shell scripts. So shell is very important for a shell script to run, and it gathers input from you, the user, and executes programs based on that input. When a program finishes executing, it displays the output. So, this is simple. You write a command in the shell. The shell will interpret it, execute it, and then give you the output. So this is how it works. Shell script is a series of commands. Say, if you want the output of three or four commands, you want the listing LS, you want the date then you write date, you want to remove a certain file, you write RM and the file name. So, if you want to do a series of commands, you can write them one after another and that becomes a shell script, and you run it, and that runs those series of commands, and that is about the shell script. The shell is the interpreter, okay. So, what are the types of shells. In Linux actually since it is an open source, it was being parallelly developed by a lot of contributors, so that's why we have a myriad of options in Linux. We just don't have one shell in Linux. There are many shells and you are free to install and use any shell you want. So, there's the Bourne shell, normally called 'sh' shell. Then we have the Korn shell, 'ksh.' Some of the Linux distributions use 'ks' and some use 'sh,' some distribution use 'bash' Bourne Again shell, then we have the POSIX shell which was the primitive shell of the Linux when it was first introduced, and we have this C shell distributions use, and we have the TENEX C shell called 'tcsh.' So, these are various types of shells. We should be concerned about the bourne-again shell because bash is the most famous shell which is being used by most Linux distributions nowadays because it is very advanced and very secure. So, we will go ahead and do all our scripting tutorials using bash, and I recommend you to use this shell in your Linux distribution. By default, you don't have to worry about that. By default, cent OS 7 and Red Hat distributions all have bash shell as the default shell. So, bash shell scripts are pretty robust and pretty much the latest ones, latest in vogue, so you should go with bash shell. It is very advanced and there are lots of good resources available over the Internet if you want to learn more about the shell. So, let's begin with trying to write a shell script and understand how it puts together a list of commands. Before we go ahead and start the shell scripting, let me tell you, I have a VirtualBox running with the Linux distribution here and what I will do is I will log into this system using ssh because that will make it more convenient. This is the shell from which I will log in to that system. I have logged in to the system. So this is a Linux system where I have installed CentOS 7 So here we will try out our shell scripting. If you are using a Windows system, you can install VirtualBox with Linux running on it and then simply you can do it this way: You can just log into that system, open up a terminal like this like I have done here. To open a terminal by now, you know how to do that. Let me just tell you again. You can go to applications and click on terminals. or you can find it in utilities, you can click on terminal, and this screen will open and here as well you can start writing your commands. So, you can do it this way if you are using a Windows system. For my convenience, I am logging it through the shell I have in this Mac system. So, we are in the same system actually. I have logged in to this VirtualBox. So anyways, you just need a Linux system to run your shell scripts, and for making things very organized, I have created a directory, where I will store all the shell script we will be learning and creating for each tutorial. You too can do it. But I insist that you should try writing all these shell scripts from scratch by hand. If you just copy and paste scripts or read other's script, you are going to learn, but you would not be very comfortable with scripting. Scripting is just like swimming you can say. You have to try it yourself to know what it is. One can only guide you, but only you can teach it yourself because this is programming. So, you have to try it in order to see the fun in it and understand. So here we have a sub-directory fundamentals. Inside it I have a series of shell scripts for this tutorial, and I'll first explain how to write a shell script from scratch, like say we write a shell script 'hello world' just the first shell script. So let me first tell you, before writing a shell script you should be very familiar with the VI editor or the vim. In Linux, you get that editor out of the box and you can create your files using that editor. So, we use that editor and if you're not acquainted with vim, then you should just learn the few basics of the editor. So I just write the editor's name and the file name which we are going to create. Now see the extension for shell scripts; you can in fact go without an extension because in Linux the file name doesn't matter. It will work as even if I don't give the extension, but still for recognizing the file, normally we use extensions for shell scripts like sh, or the name of the shell bash or ksh or css whatever it is. So here we will write a bash script, so let's name it vim hello world.bash. So now, it will open a blank file and now before starting this, let me just give you a few basics on using the VI editor if you don't know it yet. VI or vim, we just open up the editor but here normally when you open the editor you cannot type anything. If you type anything, it won't work. So first thing you have to do is you get into the insert mode by pressing I you can see here in the bottom of the screen you get the insert option now if I type anything any random stuff we will be able to view it because now the system is in insert mode if I press ENTER it's go to the next line and then we can type more stuff okay and more and more so this is how it works and once you are done with that you have to press escape you can see the insert mode goes away and then here you should go do a shift : this symbol colon comes here and if you do W it will write the file same as control s which we do in files and windows so that will save the file so here we do W : W to save the file if you want to save and exit you right W Q so that writes and then quits so this is how we save a file in room you should get acquainted with that if you are not very comfortable you can write this file anywhere say you have windows you can use a very good editor called notepad plus plus you can download that notepad plus plus this is a very good editor for writing shell scripts you can write your scripts there and then copy that into your Linux system and then execute it but it is very good to do it using vim because VM is the ultimate Linux IDE so you can use it to write Rho shell scripts and run it there so it is difficult to learn it in the beginning but you have to get acquainted if you're in the world of limits so here we first we write a shell script so we name it and open it using vim so let's clear the stuff which we had tried out right now for deleting lines here and VI you just do DD so it will really delete each of these lines so I did DD three times so three lines are gone okay so let's move on so now we have a blank file which we have entered now let's get into the insert mode by pressing I now if we begin the shell script the first line identifies which shell we are going to use to interpret the script so here I write slash bin bash because we are going to use the bash shell this line should be there in every shell script because it explains which shell is going to interpret it even if you don't put it it would run in the default but it is a very good practice to announce the shell which is going to use it as the interpreter and now you might be wondering what are these symbols this is the path of the shell so that is fine because bash shell is inside /bin directory but this has a significance now let's get back to the slide to know more this is called the shebang okay by this because I just called Sri Bank because the hash symbol is called a hash you know and this symbol is called a bang okay so this is called a shebang it is actually the pointer which tells that bash shell is going to use to interpret the script here in this example we have just assets so the SH shell is going to be used as the interpreter so anyways we have this bash shell written here and one more important thing next you should begin by writing a few comments and as for what is the purpose of the script and stuff like that so for menteng we put a hash sign but not with this exclamation okay so if you put a hash sign in the beginning of any line then what happens that line is not executed it is just a comment to let people know what the purpose of the script is okay so here we write that this is my first rap to say hello so that is the purpose of the script here you can put other information like author of the script the company name if you're working for some company or whatever you want so author is here you can write your name and stuff like that so that part is done so we have commented the script and now here you can write the Linux commands the conditions whatever and then the script is ready so here we just want to say hello to everyone so for that we use the echo command in Linux one more thing to do shell scripts very well you should be very good at Linux commands so try to use the man pages try to use the Internet and learn more and more Linux commands as they come it's not going to happen overnight or in a few days you'll learn lots of commands it doesn't happen that way if you keep on using Linux you will be faced with different problems and start learning commands it's just like use increasing your vocabulary in the English so we learn more and more words as we grow so that's that's how it happens in Linux as well you learn more and more commands as you start using it more frequently but you should be knowing the basic commands and that is enough for writing shell scripts you can always refer to the internet for knowing more and more or even you can email us to ask questions if you are stuck somewhere we are always there to help you out and then let's get back here so first we want to say hello to everyone so we write echo echo is the command to echo something or say something back so we want to say hello so I put double quotes just to make that string is a text string so that's why I want to ensure that everything works well even if you don't put these quotes in this case it would work but let's put that as a good practice hello world if you want to write more you can do that again radical say in second line I want to put some dots like this that I can do say I want to do a third line where I want to write this is my first script so that also can be done so you can just like this lines after lines you can type and then you can save the file and execute it okay so then let that be and in the last line you can write exit so that exits the shell name once you completed the shell will enter you but that is not necessary here why because see here we are running these three commands so once these commands are executed the shell will by itself exit out so exit is not required later on you will learn the cases where you need to exit forcefully from a script in case of loops and other complex stuff you need that we'll come back to it later on so here this is our first script so let's save it for saving as I said WQ write and quit another option is there you can write : X before that what did i do i press the escape and then shift alone and then WQ so the file is saved if we do the listing we can see this is our file which we created right now so our file is ready but if we execute it it would not work why because as we can see that here this file has readwrite permission that's fine and read for the group users and we'd for the other users so this is not going to execute because it does not have the executable permission this X is not present so for that what we have to do first of all we have to put the executable permission for the file to execute so when you write a shell script you write it and then do this chmod plus x that makes the file executable and then the file name okay so this is the second step don't worry we have all this documented here say here is the shell script example like one we were trying right now and here I explain you how to make it executable so these commands are also a part of this tutorial so you can make the script executable in that manner as I showed you chmod plus x this filename you can also do it in this way chmod 755 v 5 makes it readable writable and executable ok so then the file name hello if I press ENTER this will also make it executable but you can use any one of these commands so I have used this command chmod plus x the name of the file so now this is done let's clear the screen do an LS - L so now we can see this is turn to green what does that mean that the file has become executable see here X has appeared for each of the users so we can now execute this file now how to execute a script there are many ways of doing that first of all you can do this dot slash and the name of the script ok now if you do this and press enter the script would execute see that prints hello world then the dotted line which we did and then this is my first script so the script is working and even you can learn you can execute the same script by using this you can write bash because the bash shell will execute and then the name of the screen the output is same because it executes so you can execute in either of the ways you like only thing you have to remember is you have to provide the path where the script is running now since we are inside the fundament of this directory and the script is here in the same directory so we are just writing dot slash in the name of the directory bash name of the directory say we are in some other directory and if we want to run this then from there we will have to give the entire path say I go to the slash temp directory now if I run this previous command it won't run because no such file is there inside them temp has some other stuff so from temp if I want to run the same file what can I do I can write bash but I'll have to give the full path so here slash root and then I'll have to provide the path where I have crept I have crept it in shell scripting and inside fundamentals and then I have to provide the name of the file so bash and then the entire path leading to the script where we have kept it so now if we press ENTER we can execute it and it doesn't any more show the that the file does not exist so this is how a script executes you have to give a full path if you don't if you are not in the same location and if you are inside the directory of the script and you can directly run it so let's get into that directory again and start proceeding to our next spread so here we have this script to successfully run you should try it in your own hands and see if it works and you should remember the syntax the shebang first and the comments and then you start writing so here are some more examples so we can try those as well I have already written these to make things faster but you should understand and try writing each one of them yourself so that you get a hang of things so the first script here let's go through it again we have the shebang than the comments and you do all these stuffs here comments then what this crib does is we want to see the present working directory means where we are currently and we want to see what is inside this directory we want to run these two commands so in order to do that we have written this script pretty simple so we have written PWD that will show the directory where we are and LS will list the files inside that directory so here if we execute the script this will start working so let's make it executable okay so here we see that all the scripts I have written are not executable so let's make them executable all at once without having to run it again and so chmod plus X so if I do star anything inside you tree will become executable star is the wild-card character districts so anything here will be executable so now if I do the long listing I can see all have become green and got the executable permissions so that is very good now we can execute this file so let's see what happens if I execute that file so I give the file name dot slash to execute it here see we got the output the first line tells the trajectory is this here is where we are and then the second line tells the different files which are present in this directory so that is very good similarly let's move on to some other examples which we have created so this is a second example let me explain the script to you first so again we open the script using VI let's use vim you should make it a practice to use vim because it is improved editor and it will show you the script in different colors so that you understand this is a comment blue color this is a command brown color and stuff like that but if you open in VI let me just show you you would not get any differentiation so it's a bit difficult when you have long scripts the everything is in black or if you are using a black screen it would be invite so we will differentiate everything and lets you tell there is it also has many many other advanced features and easy for writing since proofs so here the second says give what does it do let's see the first line because the - - - one line so that's understood then what does it do it runs the date command so that will print the date fine and again the line and then PWD means it will print the present working directory and then it does a LS I have an L of the /boot directory that means the script what it does is it planes the current date it prints the current directory and then it lists the /boot directory good enough let's run it and see how it goes Wow so here we can see it printed the - then it printed the date and the time in the year and then the current directory and then what is inside the /boot directory so this was wonderful so you can see you you have run three four commands at a time you can format it make it beautiful and pretty printed so this is how and magically the shell script works okay so you can write all these kind of shell scripts and do stuff automatically so here number three this shell script is very important before moving to that this we have already covered executing a split you have to do a chmod once and the script becomes executable you can do LS and check LS - L and check whether the executable permission has a beard or not and then you can run the speak so next one important aspect of shell scripting is assigning variables okay variables what variables are first we have to understand and then we can understand more complexities of variables so first of all variables are values which are stored as strings and which cannot may change for each execution of the program say I want to print the name of the user who is writing this shell script so my name is different than yours name most probably so if I want to print my name I cannot just write echo and my name because if you run that script it would not equal your name say someone asks you write a script to equal the name okay so you write a script and then inside it you write echo and then you put your name say your name is so your name is Tom you write echo Tom so that is fine but say another person John is trying to run that script if he runs it will print your name is Tom so that is wrong okay so that's why we use variables in the case of variables what happens is you can assign a certain operator which will take input from the user or somehow manage to change things when they change okay let's try it out so that you can understand better here you can see this is a simple script I've done away with the commenting to make it more simple so here we have the spacious shells and she bangles here now STR this is a variable say we have a variable STR and inside it we have stored the value hello world okay and then we eco dollar STR when you want to equal a variable you have to put a dollar in front of it now what will happen if I execute this script three here it shows this command is not found that means there is some problem here let's remove this so here if we now want to execute this script what it will do we are trying to print the variable so what is stored inside the variable the string hello world so it should print hello world so let's save this file come out of it and then run that script three dot bash so once it is executed what does it show hello world so this is how the variables are stored say you want to print something else say you want to print the name of the country now we are staying in so that can be done you just change the string that is the variable value so you don't have to change the entire script or write something in eco so you can directly change it over here say we want to write India here or anything any country name so if we run it it will print India so this is how this scripting thing works so I hope you understood how to store stuff inside a variable just write the variable name let's reiterate because this is very important you are going to need all this knowledge again and again writing cell scripts so this is the name of the variable and inside it you write the value if you are writing a string so you can write it with double quotes if you're just writing a number you can leave it like that and then echo the variable name that will print the variable okay so this is how a variable is stored now let's get to a bit more advanced stuff about variables this is in the fourth script which we have written what this script does it takes the variables from the user so this is very important and interesting as well so here if we do this we want to take the input from the user so for that we use a command called read command reads and we'll take the input from the user as said read command allows you to prompt for input and store it in a variable so let's see the example what is this doing the shebang line that's fine next what it does is it touches two files that is it creator creates two blank files called file1 and file2 okay and then what it does it echoes something echo with - and we'll prove it for the user input okay so if you do this it really called the enter the name of the file to delete that means you have created two files now it will ask you to delete one of them so say you say file - needs to be deleted then it reads the this name which you mentioned with the which the user mentions as a variable called file okay and then later on you pass the command RM at the file name and then it asks you if you want to delete and then if you press yes it gets deleted so that is how the script works takes some time to read it the most important line is this read file why this file you can name it into any variable since we are deleting a file that's why this variable name is v command is important read read what it does it reads the input from the user in the previous line if you run this script you will understand better let's clear this screen and let's execute this file dot slash see it is asking us to enter the name of the file to delete like it created two files file1 and file2 say we want to delete file 1 then it asks that if you want to remove the regular file file1 I say yes that was your decision okay so now if we do a list we see that only file to his present file one is not there so that means our script has worked and it has taken input from us it was asking us a question enter the name of the file we named the file and it took that input so that is what I am trying to explain there the read command will take the input from the user here we have passed the input when the script was running that was read by this script and then it used that as a variable to remove it here it has written RA minus a and the dollar file the variable which is being read here so that is a variable because it can change sometimes if we run the same command same script and if I put file two then it will remove file two and leave behind file one you do the listing and see file one is there now and five two is deleted because our variable was file 2 so this is how we can put inputs to the user and then get take inputs from the user in fact and then execute them inside our script so read command is very important you should go through all the shell script examples we are going through here and try to use them yourself in different different cases now assigning variables in a command substitution this is also very important what command substitution does let's read another script this five this is about command substitution you can also store the output of certain commands into a variable okay say list means LS and date means the date command so we can also do that that will help us to print things in a proper way say we want to write today's date is and we want to pray in today's date so how do we do that in a shell script so first of all we mentioned that date variable this variable date is equal to the date command if you write a command it is very important to put back ticks see these are not single quotes there is a difference between the single quote and the back take the back tick is the key just below the escape button in your keyboard so that is a back tick and single quote is on the right hand side near the enter or the return key so you use the back tick and within it you write the command which you want to store as a variable so once it is stored as a variable it makes us easy to print it so we write today's day it is and then dollar date so what is dollar did it is actually running the date command and storing the value so it will print the date and similarly if you want to list the files install a list so dollar list is this so this is how we can store commands inside variables so that is also called command substitution if I execute that script but do we see today's date is this and this and the list of files are this so why this is used it is used to make shell script outputs pretty you cannot just print the date if I just write date it will print the day but if I want to make it look like this today's date is this and this are the files inside this directory to make the reporting the shell script output vary and standard so we use storing commands inside variables and then print them so these are all bits and pieces you might be thinking why am i learning this stuff because these are bits and pieces which are the fundamentals of shell scripting and when you you know try more complex scripting these will be those tools which will come in handy too if we make the script so this is the command substitution for their mean storing variables inside the command outputs inside the variables so that was done last thing about variables is how to do mathematical operations is in Cell script this is also very important and you need to know how it works so for that as well I have a few examples the sixth script master - so here in maths what happens if you want to evaluate something in Linux you can use the lead command okay we can see here all the examples are printed let's statement can be used to do mathematical functions so here we will learn how to use that say you want to do this operation 10 plus 2 into 7 okay so how it is done you just write what you want to do store it into a variable and put let beforehand that means let X is equal to so and so let Y is equal to so and so one important thing is here even you can use the previous variable and then operate on it so that is very cool because you don't know the value of X yet you just know the components and you just put it there and why what it will do it will execute X use the value of X and do other operations over it and print the result and then you print X is dollar X because it's a variable now and Y is taller Y so that will print the output of x and y and it will very fast do the calculation and give you the output in real time so I do this so it did the calculation X is this why is this so this is how mathematical substitutions and variables are stored and it is operated so you need to do this as well because sometimes in scripting we might need some automating something which needs some certain calculations so that can be done from here okay by using these operators like let okay so there is another such maths example this one you can use dollar with these double you know brackets double first bracket and then inside it you can directly write it as well so this is another way of doing it you can use the left which I showed in the previous example I'm showing this example just to demonstrate the number of ways you can do the same thing say you want to do some mathematical operation you can directly write it inside this store it as a variable and that print it equal the answer is dollar P similarly there is another way also to do mathematical operations you can use square brackets right stuff inside it which you want to calculate put dollar here and value so you should have to do this yourself and try to remember the difference in text which can be used it is all about remembering and understanding the script so that is pretty simple it's a variable so dollar and inside it you put the operation with double brackets so that is the syntax or you can do it this way more simpler and if you execute it it will print the same output so if I do this if I execute this you see you did it in two ways answer is coming the same because both are correct syntax to use that is how you do the maths operations okay now comes the interesting part here we have certain questions for you three questions which you should try to apply what you have learned in this tutorial and then try to execute them the first one I will demonstrate it to you because it is the most complex one here these two are easy I will just tell you how to do that and if you can do that it's fine if you cannot do that then I will include the scripts along with this tutorial so you will get that along with this script so example 1 is done for you 2 & 3 I will include here and then you will get it but you should not try to first see the inclusion you should try to do it yourself if it doesn't work then you should see that so ok so let's try this here first shell script what it is asking write a script to obtain the user's name and is age from input and print the year when the user would become 50 years of age so now shell script should be first understood how to execute it it should be very logical in plain English language and then you try to write it now this is you might feel this is overwhelming what is this how do I know when the user becomes 50 years of age so first of all let us understand again what it is asking it's asking us to obtain the user's name and age so what we have to do here we have to use the variable because these are variables user name and age and we have to collect it from the user so tell me what we are going to use we are going to use the read read command reads command will the users input okay so we will use read command twice one time for getting the user's name and other time for getting the users age so we have these two variables inside the script stored and then it is asking us to print the year when the user would become 50 years of age so this is a bit complex and requires some mathematical calculations so we have learnt that as well so we can use that so for that let's say how do I calculate when I am going to be 50 say I am 30 years old now so when I will be 50 after 20 years so how do I know what is the year after 20 years now it is 2016 2 0 1 6 so after 20 years it would be 3 0 3 6 right so how do I calculate that first I know the current year current year is 2016 and then I know the current age which I get from the input from the user he says he is 30 years old so I add that current year 2 to his age - I mean I did the difference I mean now he is 30 so I subtract 5th 30 from 50 and get 20 so after 20 years he would be 50 so I add 2016 to 20 and I get 2036 so this is the logic so let's just check how the script is going to work I have already written this because we this was a bit complex for you at this stage but you should understand each and every line of the script and try to write it to yourself without seeing it and try to execute and if you go wrong just check the syntax so that is how you learn so first of all we want to know the current year so current year you can know it in a number of ways either you can ask the user and use the read command what is the current year and then the user will type it but I have done it in a more sophisticated way where the system will fetch the current here so you should learn this if I write the date command with plus the percentage Y and this syntax then it prints the current year you can try it outside the script as well so I am outside the script so if I just write this command it shows 2016 so I get the year from this command so I use this date command plus y which gives the year and store it as a variable called car underscore year for the current e then I ask the user enter your name and then read the variable as name ok then I asked the use of the age and read the variable as age ok so that is done then I will do the mathematical calculation there I write 50th year is equal to the 50 minus the current age say his current age is 30 50 minus 30 that is 20 so after 20 years he will become 50 so that is this calculation plus the current year 2016 if I add them that will give us 2036 so the user will become 50 years old in 2036 so we print that hello dollar name dollar name will be the name which has been captured here after asking the user so hello that user name will be printed you will be 50 years old in dollar 50 at the air so this variable so after the calculation of this entire thing whatever value will become it will be stored here that will be printed here so if I run the script let's see what magic happens example one the script so it's asking me to enter my name say I enter the name John asking the age I write 30 it's asking hello John you will be 50 years old in 2036 so that is wonderful the cell script automatically calculates stuff and lets you know the only thing is you have to do it properly now let's move on to the other two scripts and I'll tell you how these scripts actually would be done but you have to try it yourself and I'll add these scripts to help you with them or I will do it right now and add it there but you should try this yourself so it's asking to write a cell script to create a directory called tests 0 0 inside slash temp and 3 blank files inside it and list them so this is very simple first we have to create a folder inside last time called test 0 0 3 files inside that and then list them so let's write the script rim then example two dot dash inside it first what do I do I write slash bin slash bash the shebang then I write examples - as the comment then what it is asking me to do it's asking me to first create a folder called test zero zero insights last time so create a folder I write the command mkdir test zero zero that is done and inside where /tmp so that gives the anti thing and then it is asking me to create three files file zero one five zero 2503 i suppose yes and then it's asking me to list them so here the folder is created we can equate for informing the user folder test zero zero is created in flash time that's fine now I create three blank files for that we use the touch command slash temp and then test zero zeros because we want to create these files inside this directory so let's first enter the directory that would make things simpler so we write CD we enter the directory and inside it we do touch file zero one five zero two and five zero three that is good enough now we can echo again files created then it's asking us to write to list those files so let's do the simple command LS - L because we are inside this directory already so this would execute as well so this is our shell script is ready for the second example now we will put executable permissions for example to the bash that becomes executable now we execute it here we've made a mistake we have not written slash so here as corrected now here if you make these kind of mistakes you should try to read the this is also a very good learner because it's good that this happened you can you can check the output bad interpreter bin bash something I knew from there that I have not put the slash so if you have these kind of errors you should go back to the script and check what the problem was like we miss this slash so it showed that the interpreter is not present because we have slash bin - we don't have been bash with it so the error now we will be able to run it successfully so now we again try this so first what does it show folder test zero is created in slash temp files are created and it lists the files so our script is working so second time is fulfilled and the third script what it is asking is writer cell script to delete files 0 3 created in the previous question and also print the time after deletion of file this is also simple it's asking to delete this okay so let's write another script 3 dot - again this time we need to be careful while typing bin slash bin slash bash he bang is done comment this example 3 and then what we do it's asking us to delete the has to delete file 0-3 inside the directory which we created slash times last test 0 0 first thing we do is we enter slash damn that's test 0 0 so once we have entered what we can do is we can use the remove command and zero three okay so that is done once it has done it we can list just to check file three is gone or not and then it's asking us to print the time after deletion so I just write date so it gives the time as well so that is all the script is ready now we will have to pour this as executable and now we execute this file see it's asking you want to remove the fat I say yes so the file is gone now just file1 and file2 are left and after deletion the time was this so this is pretty simple and this is how you write shell scripts and execute them so this is a very important because if you want to move into the next level of shell scripting you will have to learn about the conditionals how to handle when certain conditions are given to a shell script and then if you have repeated tasks to undertake then what you need to do you have to run some certain loops and loops and conditionals can also go hand in hand together to handle some complex situations arising when you are running our shell script to automate certain tasks so this is a kind of a bridge between the admins now shell scripting and the basic so this is a very important piece of lesson so you need to understand each and every basics which comprise this course so let's get going first of all loops in shell script what a loop loops are a programming tool that help you to execute a set of commands in a repeated fashion so what is it actually say you want to print your name ten times say if you want to print your name one time what would you write in your shells for you would just write equal and then give some double quotes and write your own name like this let's go to the turbulent here I have a VirtualBox running this one and I am connecting to the same box using this terminal so let me just stretch to remote login I know the IP address of that box so bastard so here we are and she'll of the root so I log in as root so that I can run each and every command so we are not blog by any of for access reasons so then let's see within here here I have a directory called shell scripting inside which I have all the sample all the scripts the samples kept and you know today we are doing this loops and iterations so let us enter that directory and see what is in the area we have all various kind of example files I would be sharing all these files along to you so no worries and we would be running each and every file and checking what is inside it so in any case you are going to know through this video so what is going on so first of all as IRA let's clear the screen and what I was saying is here we have certain loop examples say we you want to do something in repeated fashion like you want to equal your name want to print your name so what do we do we just write eco and then you type your name Center then what happens your name gets printed and if I write this inside shell script the same thing would happen but say you want to print your name ten times so what would you do then you no need to you do you need to write this command ten times inside the shells field does that sound good no it does not because shell script is something which should make your stuff easier which we should automate things so you should not be writing ten times the same format if you want to do that ten times so for such situations use certain loops okay loop would execute a command according to the situation I mean according to your instructions and the number of times until certain conditions are met so it would just reiterate do it again and again and again until the condition is fulfilled say you have asked it to print the name ten times it would do one time second time and check every and check the count again and again once the count reaches ten then it stops so you get your name print at ten times so that is how these things work the loops so let's try out what kinds of loops are there and then we will try out each and every loop and understand the functionalities so first of all we have the while loop the while loop is one of the interesting loops and it this kind of a loop which executes once under certain conditions like we declare it while so-and-so conditions are fulfilled then do this so that is how it works then we have the for loop will go on and understand what it is and it is a very popular new free loop command which is used and then we have the until loop and then we have the Select loop as well okay so these are the four kinds of loops these are the four kinds of loops which we used you we have this these are the four kinds of loops which we a so we have let's discuss on now let's discuss in detail what each and every of this loop does the while loop for loop until loop and the selected first of all let's move on to the while loop when explaining I have not I've chosen not to keep the definitions for each loop and because in shell script you should not be bothered about the definition of the while loop or or all the theoretical stuff you should be unable to understand what each thing does and how it works so that you can implement in your future scripts so I have chosen just to keep a script here and explain what it does and when you understand it that way that what the while loop does then you would be able to implement and apart from that you also learn the syntax in which the while loop is used so I have done this for each and every thing which we are discussing in this tutorial we will just discuss examples the syntax and the execution so that will help you to in order to assimilate what is each of these conditionals these operators are doing and so that you can use it in your scripts so in case of a while loop just study this transcript what is it doing first of all we are setting a variable a is equal to zero sure enough and then we move on to declare while dollar a is less than ten - LT is a operator which our number actually where this LT is stands for less than so when we are telling that while dollar a is less than ten do so and so the stuff while this is greater than zero then do this stuff and then we exit after writing done okay here you can see that there is just a shell script I have done this intentionally I have not included any definition for the loops which we are going to learn or the conditionals because if you want to really do shell scripting you just have to understand the concepts and not remember the theoretical aspects like the definition you should know what is a while loop what does the syntax whether that is used when we do a while loop and finally how to execute a while loop and under what conditions that that will work these are the important things the understanding of the logic is the main thing here instead of remembering theory political aspects like what is why loop what does it stands for and stuff like that so first of all let's study this shell script which uses a while dude okay the loop and this is a nested loop as well so that would help us to know better nested means a loop inside a loop so you have two conditions being used here so what this does then we will execute it in our shell and just check it out so first of all let's study each and every line of this script and then try to execute it once and then we will be good to go first of all let's see what it does it sets a variable a is equal to zero correct and then there is a loop while is less than ten you have used this operator in the previous session so this is just a less than operator while E is less than ten this is a loop condition that if is less than 10 then you do set another variable that B is equal to dollar a okay and then ye dollar be the new variable is greater than zero then do this that means it will echo that variable okay and then it does a mathematical operation it subtracts one from the variable and then that that loop is done otherwise it adds one to the variable so this might seem confusing right now so let's go and execute it and when you see the results then we will come back again and then understand what happened okay so first of let's list for this inside I have already kept this wild or bash this is the same script that is being displayed here the while loop script so here it's the same script I have typed it to save time I have tied it beforehand and let's execute it let's check whether this file has executable permission yes it has if not then you can do chmod plus X and the file name and then you can execute it with dot slash okay so now if I press ENTER what do I see a pretty pattern of numbers so first it is zero printed then 1 0 then 2 1 0 then 3 2 1 0 4 3 2 1 0 what do you notice from this pattern there is a series of numbers here and then in the second row there is a series of numbers which has one subtracted from the number on its left like here it is 2 so this is 2 minus 1 and then here it is 4 is 4 minus 1 3 stuff like that ok similarly if this is 1 then 1 minus 1 is 0 and now if this is 0 then you don't have anything printed here because the loop exits by them so this is a pattern which we have tried to make now let's understand how it worked by looking at the script again first a was set to 0 and if a was less than 10 which is the first loop then we had to do this and that thing okay so what was that if a was less than 10 so in the first case when a was 0 it was less than 10 so the loop goes here it sets B is equal to a so now B becomes 0 now it's asking it again in the second loop that if B is greater than 0 which is not the case in the first time then we had to do this but that was not the case so what it does it skips this loop and goes directly to here it adds one okay so what happened exactly is a was zero it was less than ten that condition was true so it entered this loop and then here B becomes a because here is 10 B is dollar a so B becomes zero now then it asks again if B is greater than zero so first time B is zero which is equal to zero not greater than zero so this loop becomes false so this exits its loop and comes here and then that job is done so it just echoes the first character which was this zero okay the second run what happens when it loops through the next conditions because now a was incremented by one so it goes into the next condition if a is less than 10 that is true again enters here now at this point of time B becomes 1 and this condition now becomes true because B is greater than 0 and it equals B so there we get this one because B is greater than 0 so it equals B so B now was 1 so it prints 1 okay then it goes on and does it again and again I ask you to just write it by hand in one script and then read and understand each and every line again and again ask yourself think over it there is no shortcut to understanding what it is doing but you have to study the script don't get puzzled by all the symbols the courts and stuff like that which comprises a shell script just understand what it does so while loop is used when you want to mention a certain condition that if a is less than 10 then do some other command okay if a is greater than zero then do something okay here you can use here we have done a mathematical operation you can also do something else like say you're wanting to print your name and your name only if your age is greater than 20 okay so first what you can do it using this while loop as well first you will ask the user of the name okay and then store it in a variable and then you can ask the user the age store it in a variable say B and then you can run this while loop that while age dollar age is less than 20 then do nothing so exit and say if greater than 20 then print my name okay so you can write eco over there and do stuff so these are the various types of examples where you can use the while loop so you go through this again and try it yourself if you have any questions you can always ask us and we will be ready to help you you can mail it your own script if it is not working properly so we can fix that as well so next loop is the for loop the for loop here we have a simple example to span through the given list of numbers like here we have a list of numbers 0 1 2 3 4 5 6 7 8 9 so far look what it does it reads each and every number in the list number or names or whatever you type it in a sequence and then it can do operations on that like say here what we are doing we are setting a variable which changes into 0 1 2 three four like that in sequence and then for each sequence we run we just equal that number so what we do for varying zero one two three four till nine we do echo the wire so first time it runs it goes and reads the variable as zero and sets the where value as 0 so then we echo where so it equals zero and next time it sets the where as one so when we go where its prints 1 and so on till nine so what happens if we run the script it would just print 0 1 2 3 up till nine okay automatically because the loop will run again and again for we're in 0 print 0 for rare in one print one so this happens in loop so it will print nine numbers so here you can see the utility of the for loop and how it is different from the while loop fitted and while we had a condition that if something is less than something then do something if something is greater than something then do another thing so stuff like that but here we have a list and ask it to execute something according to the list again and again so if you want to sit here do things in iteration for a list of subjects then you can run this so let's run this loop here we already have the script for the for loop let's check this script out for very in this diseases equal dollar wealth so we can use it to slash far so we execute this see we have a list of numbers 0 1 2 3 4 5 6 7 8 9 so this is how the for loop works let's use or look for another interesting example for-loop can also do interesting things like just study this shelf here what we have done for file in you can see this capital letter stuff fight this is not a command this is a variable okay so we are setting a variable that file is a list inside etc' directory okay so what we are doing actually is here we are trying to do et Cie / and star you have known by now that star stands for deleting I mean when you have used deletions you might have done RM minus RF etc' and then say star for deleting all the files and directories inside the it is a directory and stuff like that so this Astrix of star is the wild-card character in Linux well which denotes that all the files which start with the letter n and that can be anything after that so it starts with them and anything after that so what we are doing here is we are using the for loop and assigning a variable which stores all the file names inside e.t.c which begin with n ok and then we want to print those names of the files so that we get all the files which start with the word and so this is pretty interesting now let's see let's run that script or through the name it was this now I executed it gives me a list of files of etc' directory which start with n so that is how the script ropes now this is a pretty small script but very powerful you just remember how for loop is used here first of all for is used to declare a variable inside which you have an area of values like in the previous examples we said that for we're in 0 1 2 3 up till 9 so similarly here also we tell it that it is the error of values which is all the files which start with there and then we print so here if you want to store a series of values an area or a sequence then we use the for loop and it is pretty useful and certain certain exists or shell scripts where where we need to list array and then execute something over it in some of the future lessons where we have of some advanced shell scripting you will be able to understand more about the for loop and how it is used right now you can just try out such simple examples of the for loop so let's move on to the next loop so that is the until loop the until loop is a loop which will also do certain things like the for loop and the previous loops which we have used until a condition is met so this simple script will help you to understand if we set a variable a is equal to 0 and until not dollar is less than 10 to echo a so what it does you have to run the script once and then know for yourself see we use the loop to do the same thing which we did with the for loop okay so what was the difference here told it that is zero and until not a is less than ten eco a and increment a by one tell that tell the script that until a is not less than 10 you just increment the variable by one and print it so what it does first a is zero it is less than 10 e is equal so zero is equal four and then it increments the variable a by one so now a becomes zero plus 1 that is 1 then again goes to the loop 1 is also less than 10 so again it equals a which was 1 now so one is printed here then it increments a by 1 so a becomes 1 plus 1 2 and again goes into the loop so 2 is also less than 10 then 2 is e code so here we get 2 and so on again and again until at last when 9 plus 1 becomes 10 in the final loop and then it is not less than 10 so that loop is done so it directly skips these lines and comes to the end so until loop will start doing stuff until a certain condition is met when that is met it goes to done so this is how look for you can see a family a pattern all the loops work in almost similar fashion but they have different utilities while loop until a certain condition is met it works and here for loop there is a array and until loop again just like the while loop you have a certain condition to be fulfilled and up till that it works now it is interesting to note that this until loop is available in the bash script there are certain of the scripts where I mean the shells where until loop doesn't execute and people have to work out using the for loop and the while loop combination so you can do the same thing using multiple versions of the loops but you should know each and every syntax so that it you become empowered with all the tools to write good shell scripts so next comes an important loop Lu looks a bit complex but it's pretty useful as well the Select loop this is all specific to bash so you should try it in a bash shell and anyways bash is one of the most powerful and secure shells which are available right now so you should try writing bash scripts if you are into shell scripting so here we have a select loop we're what we do we give option to the user to select a drink which could be tea coffee here we have a list of conditions that tea coffee water juice soda all or none so this is a menu which we provide to the user so we use the syntax select drink is the variable inside it there are all these values which we want to list okay now what happens there is a condition that is dollar drink in within all this if the user selects tea coffee water and all then we asked the user to go to the canteen if the user selects juice or soda then we say that it's available at home and finally if the user selects this none then we ask the court to exit by using break statement ok and if the user selects something else other than this menu then we print error invalid selection so we write eco invalid selection then once this is done we escape out of it ok so the case ends here case ends with esse and that is the syntax so this is the syntax when we write select drink drink is the variable in the list of the menu then du and then inside it you write the case and then you end the case ok so I hope you understood this script again let me iterate it you have V we are giving the user a menu and then asking the user to select any of this beverages provided in the menu now if the user selects de coffee water and all then we will print that you have to go to canteen and if the user selects juice or soda then we will plenty it's available at home so the this select loop helps you to provide a menu to the user and based on their selections we can give them certain outputs so this can be useful in many other cases as well like the we will give a menu to the user to select 3 colors like any of the three colors now if this user selects red then we say that he is angry today now if the user selects green we say that he is jealous today or something whatever the color signifies so that way we can interact with the user as well so this is a pretty important loop so let's now check this shell script and see how the loop works so the select loop here is that loop which we were discussing so I have typed it in here and we have the list then we have the case that what happens what to print when they use a selects so and so stuff if there is just like juice then we print this and if they used to select something else we invalid and if their user selects nan V make it exit so let's run that script so far when we run the script we can see that we are provided with a menu with numbers okay so now say the user selects two which is coffee so now we can see it's prints go to campaign which is which is what we did now in juice I think we had said that it's available at home so say the user selects for now it says yes it's available at home if the user selects all of it so that is not at home so it will have to go to the canteen so go to candy now say the user selects something which is not present in this list la9 invalid selection so our scripts are working perfectly and say the user selects none so none is here number 7 so week 7 then we exit so that is how the select loop works now you can take your time after learning each loop you can pause the video and think over it and try the command and then move on further for the sake of completion and moving on to the next the conditionals okay the conditions are very important a very very important part of a shell script here what happens most of the cases when we run a shell script we are faced with conditions if this happens do this if this happens then do this if not then do this and if there is certain other condition then is the exit out of the shell and stuff like that so conditionals are very important this is the normal in text by which we use conditions so conditions normally conditionals have if-then-else statements and we have another statement called as if okay I live written here so what we do if and inside square brackets we have certain expressions which has the condition inside it and then and then we run certain commands say if there is a certain file inside the etc' directory if that file exists then we run the file exits else if that is not present then we eco that it does not exist and so on so the this else else if if all these are various conditionals which can help you deceive make decisions when running an algorithm so this is how it works so let's do some real scripts and see what exactly did the first here we have a shell script where we ask the user to enter the login name login name means the name which we are using to login into the shell like this one here you can see I have logged in as root user I can even check it using Who am I yes so I am the root user okay so that is the username it is asking so if you run the script the script will ask to enter your login name hey we have entered root then what it does it reads the user input you know from the previous session that read command reads the variable inputted so now it stores the name of your login user now what it does I say that if dollar name is dollar a user then this is a environment variable which stores the name of the user you can check it out here if I print a Codel user I can see the answer is root so that means this is an environment variable when you log into the system the operating system has some environment variables allotted to the user so dollar user is the variable which tells the user name you can even know the shell that user is using using dollar shell so these variables have not been said they are just available from the environment by when the user logs in by reading from its profile there is a directory there's a fire in fact you can sorry you have to do this in the home directory and it's a hidden file so we give a less safe L here you can see that bash profile door bass are see these are the files which store the environment variables so we can open this way - see when you have spare time you can go through these files and understand exactly what these files are so here you can see certain variables are said certain alias commands I'll say here okay there are other such files as well like this one which have environment variable set sorry I did the same thing again it's inside slash root here here such an environment wills and parts are exported okay so these are something about environment variables we'll discuss them more in further sessions so here are our interest is this use of a variable dollar user this is an environment variable to stores their login name so here we are asking the user to enter his login name and then we are storing it inside a variable called dollar name and then we are comparing it with the dollar user environment variable and now if the user entered name and the environment variable matches then we say that hello user how are you today and if in case user login name the user types is something which doesn't match the actual Linux user who has logged in then we type that you are not the user who are you okay so this is the thing the script does let's then check that script here and try it out this is a conditional script again you can see first for people we use Eco to print that enter your login name their user does so we read that input using read command and this is the if conditional the syntax as I said if and then inside square brackets you write the condition if so-and-so is equal to so and so or if something is not equal to something or if something exists or not so these kind of conditions you can write here I'll tell you how many kinds of conditions you can use so first now we have a equality condition here if some variable is equal to some variable and it with the semicolon equals something else equals something else or do something else okay so this is the syntax in which we have written the script let's run it conditional one underscore bash so first of all it's going to the first you know echo that asking us our login name say I write my login name is Ruth hello Ruth how are you today and the script exists so it works because our name and our shell login the same ok so it is working correctly now say I am root user as you can see here but say if I write something false like I'm not a root user I'm Tom so it checks it compares it with the dollar is a variable and finds that dollar user is root but this one is Tom so it is asking that you are not rooted what so this is how this script works so this is very interesting and very useful as well okay now let me before going into the second script let me go to this slide and tell you a few more things as I said this condition in here like equal to or something you can use other conditions as well like - d - - and - e inside the square bracket if you write - d and give the path of a directory then it will check if the directory exists or not if it does not exist then it will give false okay if they if it exists then it will run that command say you want to delete a directory if it exits so you can write minus D the path to the directory if it exists then you write RM command and delete the directory else you print the directory does not exist so this is how you can use these expressions for file also the same thing if a file exists or not if you do - E it tells you the file exists or not okay if you do - F it checks if the path given is a file - D if a path given is a directory so here we can use these expressions called file operators to check files and directories now let's come back to the second script the second script is a bit more complex but pretty interesting first of all we echo that enter any number which is less i mean greater than 1 but less than 10 so the user will input a number so it will read that number from user input now we are giving a condition in F that if the number is less than 10 then you go into another loop so here we are using nested loop if loop inside another if loopy say you have to do two conditions you have to check two conditions then you use this first number is less than ten then check again if the number is greater than one if that both are true then you multiply number into number that is the square of the number and then store it in a variable here number into dollar number and then that variable is stored and if that happens then that variable is equal okay after that calculation happens we call that variable because we are storing we are you telling that Eko dollar number into dollar number which is equal to this operation so that how it happens in runtime and we equal that okay say this condition are not met or one of the condition fails then the loop exits two else then we say it is a wrong insertion okay or say the second one fails then again it goes to else like this fails it goes here this fails it goes here okay so the user is asked to input again because this is wrong okay so this is how the script works let's try that script again here we have this let's go into the second strip and dish - okay so this is the same script which we discussed let's run it and then check the output conditional - dot - it's asking to enter a number which is greater than 1 but less than 10 so say I died 5 so what it does it checks that whether this condition is fulfilled or not it is less than ten or not it is greater than one or not so once that is fulfilled then it goes to the den close and then does this operation five into five equal to 25 so this is how this works and it works perfectly let's check if the loop if we write something wrong the loop detects it correctly or not one is less than so we have to give a number say a even-numbered 9999 is clearly greater than 10 so the condition will fail so it writes strong insertion similarly say I give the number 1 so 1 is not greater than 1 so again wrong insertion so this is how it is working we are doing multiple loops inside it nested and then checking all the conditions we want according to the result we print the output okay and one thing you should remember in the syntax for the if loop is if loop should have a square bracket with the conditional then it should have a semicolon and then and then you write the statements after then if you want another loop you can keep another loop you can write use else if you want a third thing to be inserted but always close the if with the fi okay see here we have two nested ifs this one is closed here this is the loop which closes here so there is one big loop inside it there is another small loop you should study this and try yourself so that you will get an understanding if you have questions you can come back to us any time and then finally this this one as I said inside the if loop in the square brackets we can check the existence of files and directories paths so we use these file operators for that for an example we have a shell script here for file existence check this one check file menu either's you'll understand this is a pretty simple live loop again say if we have stored a variable that the file is etc' hosts okay we want to check whether this file exists or not so what do we do we use this operator - f as I said it checks whether a path exists exists or not so we have given the path that etc' hosts is the path where a file resides and we wanted to check if a file that means if this condition is met then we say that file is found and if this condition is not met we say that file is not found so simple and we do Fi to exit the if loop let's run this and check what happens vas it shows that yes it is found so that is great now let's modify it a bit and write some random path which does not exist so you should check there and fail and show us that it does not exist so I write x X we don't have this directory so it should fail and we run it again so it shows clearly this path is not found so here we can use this if loop to check the existence of certain files and we can know that it exists or not so I am fixing this script again and stirring it so that is done so these are all we had to learn today you have to go through this it was a lot of new stuff you have to know when to use which of these loops and conditionals and practice a bit then we will follow up with some advanced shell scripts which will help you to understand these better and try to implement it in real-world situations so we have a question for you in shell scripting what does dollar hash stand for option 8 will return number of error option B it will return the number of parameters that are passed as command-line arguments option C error and option D all the above are incorrect so put down your answers in the comment section so as to check if you have answered correctly so this brings us to the end of this session if you have any queries do comment below we'd love to help you out also do subscribe to our channel so that you never miss out on any of the upcoming videos thank you Oh
Info
Channel: Intellipaat
Views: 61,984
Rating: undefined out of 5
Keywords: shell scripting tutorial, linux tutorial, linux shell scripting tutorial, linux commands, shell scripting tutorial for beginners, shell scripting training, scripting tutorial, shell scripting, shell script, bash tutorial, unix commands, Bourne Shell and Programming, Bash scripting, Unix, Shell Programming, directories, Memory Management, Using Shell Variables, bash scripting tutorial, bash shell scripting, unix shell scripting, Intellipaat, shell scripting crash course
Id: 9ckXibjManw
Channel Id: undefined
Length: 108min 4sec (6484 seconds)
Published: Tue Jul 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.