Bash Scripting on Linux (The Complete Guide) Class 05 - If Statements

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
thank you so much for tuning in to learn Linux TV your source for Linux related fun and learning I love producing Linux related content for you but I can't do it alone if the content on this channel has been helpful to you then please consider supporting learn Linux TV and one of the ways that you could do that is by becoming a patron which will give you access to exclusive perks also be sure to check out my latest book mastering Ubuntu Server 4th edition and while you're here be sure to subscribe new content is uploaded each and every week thank you so much for your support I really appreciate it now let's get started with today's video [Music] thank you so earlier in the course I mentioned that bash is kind of like a programming language actually bash is a command interpreter or shell but it does indeed have a lot of features that are quite like programming languages and in this video you're going to see the first example of that more specifically what we're going to do in this video is take a look at if statements so let's just Dive Right In and get started [Music] the scripts that we've been writing so far are only somewhat useful the whole idea behind scripting is to automate something and part of that is that we might want the script to do something different depending on the status of something else now an if statement is something that you've probably already heard about if you're coming from a programming language writing scripts is essentially the same thing as programming and Bash actually uses quite a few components that overlap with programming languages the if statement is just one of those so what I'm going to do right now is give you an example of an if statement and then I'll explain it so go ahead and create yet another script I'll give it the same name so I've typed the shebang something that we'll always be doing and let's go ahead and get started I'll create a variable named my num I'll set that equal to 200. and let's jump right into an if statement so to create an if statement what I'll do is type out if and then an opening bracket after that we'll press space that's very important you need that space in between we're going to reference the variable that we've declared in the previous line my num Dash EQ and like I said I'll be explaining all of this here very shortly 200 closing bracket so we have a test statement there and then what do we want to do if that statement is correct what I would like to do is Echo the condition is true and then I'll type the word if backwards to close out of the if statement so what exactly is happening here well we already know what I'm doing right here I am declaring a variable named my num and I am setting that equal to 200. next we have an if statement an if statement begins with the word if then after the word if we have something right here it's not always going to have brackets like mine does more on that later but what it will have is some sort of test case we want to evaluate something in this case what I'm doing is I'm trying to find out is the variable my num equal to 200 well we know that it is because we actually set it to be equal to 200. so this condition right here is always going to be true unless I change the number up here when I declare it so after I type if and then whatever I'm testing for on the next line I typed then what do I want to do if that condition actually evaluates to true I have four spaces here that's very common we want to indent just to show that this is part of what happens and that part of the original layer or the if statement initially if that's true I want to Echo the condition is true at the very end we end our if statement with Fi which is simply if backwards that lets bash know that we're all set we're done with the if statement you can go ahead and carry on so I'll save the file and what I did is I held control and pressed Z that's something I'm going to be continually doing that sends the Nano Editor to the background some distributions won't let you do that but if your distribution does allow that then it effectively allows you to send the editor to the background just thought I would share that fun tip how to get it back well you type FG and it comes back anyway I'll minimize it yet again and let's go ahead and run the script I'll go ahead and Mark it executable and then we'll run it the condition is true so this particular if statement is not actually all that useful if statements are more useful when you have a condition that can change in this case the condition will never change unless I change it manually right here so what this is doing is just checking to see if it's equal to 200 which it is because that's what I set it to and since that statement is true then it went ahead and printed this line right here now right here we have Dash EQ that stands for equal there's different checks that we can perform within the brackets Dash EQ is just one of those and we'll explore that again shortly but just to make sure that our if statement is actually working I'm going to change my num to be equal to something else let's go ahead and run it and see what happens well nothing happens the condition is false the echo statement is only going to execute if the statement is true which it no longer is is checking to see if this variable is equal to 200 it's not because I set it equal to 300 so this here is never going to carry out in order for this to carry out the check has to evaluate as true which it clearly isn't going to do now what I'm going to do is set that back to 200 and I'm going to add yet another if statement this time I'll check the my num variable yet again and I'm going to check to see if that equals 300. I set it back to 200 so obviously that's not going to be true but it doesn't matter for now let's just go ahead and roll with it anyway what do I want to do if the statement actually evaluates to true I will Echo something the variable does not equal 200. and then yet again I'm going to close that if statement with Fi now no surprise here I think you already probably know what it's going to do and it's true well of course it is I set it equal to 200 here I'm checking to see if my num is equal to 200 which it actually is going to go ahead and print this statement right here the next if statement is going to check to see if my num is equal to 300 but it isn't so this right here will never print so what you could do is have as many if statements as you need to get the job done but what I have here is not really all that efficient I mentioned earlier that you don't want to repeat yourself as much as you can help but you should also avoid unnecessary code as well and we definitely have some unnecessary code here so what I'm going to do is erase this line and this one here and I'll even remove this fi right here and instead I'll type else and that's actually the only change I'm going to make rather than having two if statements I can combine both of those if statements into one which is exactly what I just did what if else does is it first checks some sort of criteria here just like normal and if the statement checks out it's going to Echo or perform whatever command you have here that's going to carry out else is actually going to be evaluated if this statement is not true so if I was to change this to 300 then this check here is going to fail this will not print the condition is not true anymore I made it untrue so it's not going to print the condition is true instead that's going to activate else and what else will do is check the if statement if it didn't evaluate then it's going to do this instead and as you can see it does exactly what we expected it to do so now if you weren't already aware of how to write an if else statement now you know here's an if else statement you type if we have a check then what do we want it to do if that check checks out if it doesn't what do we want to do instead we type else and then what we want to happen instead if the first command doesn't run it's as simple as that now pay special attention to the fact that we combined two if statements into one this is something that we're going to be doing throughout this series trying to find out how we can create a script with as few lines as possible we definitely don't want to have anything that's unnecessary something that's not needed and nobody's perfect I'm sure I'm going to have all kinds of ways that you could find on your end that you could further consolidate the scripts that I write on my end but the point is not that the point is your mindset should always be focused on consistency efficiency basically don't repeat yourself unless you absolutely have to and try to achieve what you want to achieve with as few lines as you possibly can and as your knowledge grows you'll find better and better ways to avoid unnecessary commands and well consolidate your scripts in some way or another now what I'm going to do here is actually add an exclamation mark in front of the variable that I'm checking now what do you think is going to happen when I run this well I'll save it and then minimize it let's go ahead and run it and see if you're right it says the condition is true but hold on a minute the condition is true why is it saying that my num is 300 and here I'm checking to see if it's equal to 200 this statement is not true well actually it is true it wasn't lying to us but this exclamation mark does right here is it actually reverses the check so literally what this is now saying is if my num is not equal to 200 that's what this exclamation mark is going to do it's going to negate the text basically reverse it flip it around it's going to do the opposite of what it would do normally and that's why this printed right here the condition is true it actually is I'm checking to see if my num is not equal to 200. but you know what this isn't the best use case for an exclamation mark so I'm going to get rid of that in this case the best way to check if something is not equal to something else is instead of using EQ which represents equal we could type dash n e which means not equal or checking literally specifically to see if it's not equal to 200. it says the condition is true and that's correct my num is not equal to two hundred so this statement is correct obviously I should be adjusting the text down here that could be a bit confusing but we're going to ignore that for now now moving on from there there's other checks that we could perform as well for example we have greater than that's if we want to check to see if something is greater than something else so here we're checking to see if my num is greater than 200 so let's go ahead and run it make sure it works and it does so now you know that you could use GT for greater than if that's something that suits your particular use case next what I'm going to do is give you yet another example so I'll just clear out of everything here and what I want to show you right now is that you can actually check for the presence of files on the file system but how do you do that well what you do just like before is you type if we're going to include an opening bracket we'll type Dash f and in my case I'll type tilde and then slash my file closing bracket then we'll Echo the file exists then else we'll Echo the file does not exist let's close the if statement and then I will save it let's exit out I'll explain it in just a moment but let's see what happens when I run it foreign does not exist and that makes sense because if I cat out the contents of the script file that we've just created is checking to see if there's a file named my file and because I didn't actually declare a specific directory to change into and also because I'm declaring right here that I want to look in my home directory which is what the tilde represents that shorthand for your home directory it's looking here in my home directory for a file named my file when it ran it said the file does not exist and it's right so what I'm going to do is create the file and to do that I can simply use the touch command this is a standard Linux command and what this will do is create a file if it isn't already present but if it is present it'll update the modification time of that file and the file that we're looking for is my file if I run the script again it tells me now that the file exists if I remove it now it's telling me that the file does not exist now what we're seeing right here is our first script where the output changes based on some criteria on the file system if my file exists it's going to tell us that the file exists if my file does not exist well it's going to let us know so let's go through this real quick I think the last part of the script you should already understand what that does so when we set up our if statement you might be wondering what exactly does dash f mean well what this is actually representing is a check for a file that's what F stands for f is for file also notice that we're not using dash n e or Dash EQ we use statements like that when we're checking integers but if we want to test for files or folders we'll use Dash D or Dash F instead so if it's a directory that you want to search for in that case you'll change the dash F to Dash D other than that the rest of the if statement and the way that I've designed it is exactly the same the only difference is how we're checking for something is still the case that the if statement needs to evaluate to true for the then portion right here to carry out but again the difference is what we're checking for in this case the existence of a file now before I go on to the next script in this particular lesson there's another command a Linux command that I want to make sure that you are aware of and that is the which command you could use this command to find out whether or not an application or basically a binary a command is present on the file system so in this case I will run which against h-top h-top in case you didn't already know is a very popular system resource monitoring utility just beyond the scope of this series however it's a good example it's something that I want to make sure is present on the system and the which command will enable me to find out if H top is actually present is it present well let's find out now in my case h-top is not installed if it was I would have seen some sort of output here so h-top is not present on my system which also means if I enter the h-top command nothing happens now it's given me the command that I can use to install htop right here but we're going to ignore that for now let's see how we can actually utilize this in a script now that you understand what the which command does and let's see an example of a script that's actually somewhat useful so what I'll do is create a variable named command and I'm going to set that equal to slash user or USR it's abbreviated slash bin slash h-top basically the fully qualified path to the command h-top that's what I'm setting the command variable equal to next what we're going to do is check the contents of this variable to see if it's present and since we're looking for a file we'll need to make sure that we have a path right here inside that variable if you enter something else it's not going to work right we're not going to get into that part just yet we're going to keep it simple and we're going to check for the existence of command in this case command is equal to user bin h-top just like that so what do we want to do if the command is present so we'll type then and then we'll Echo dollar sign command is available let's run it so it's going to Echo that statement right there and then if it's not installed or it's not found alt is going to trigger in which case we're going to Echo something completely different command is not available in this case we'll start it off with sudo apt then we'll type update Ampersand Ampersand sudo apt install Dash y h top then what we're going to do is close out of the if statement and finally we will go ahead and type the name of the variable right here with a dollar sign so what I'm going to do right now is run this script if it works well it should actually tell us whether or not the command is available if it's not it should go ahead and install it for us and either way by the time it gets to the end of the script it should go ahead and run it now again h-top is not installed so let's go ahead and run it this is going to be fun it tells us right here it's not available so I'll exit out here and I'll clear the screen now when I ran the script it actually did install h-top so when I run it again we shouldn't see nearly as much output as we saw the last time so let's see what happens it just runs just like that super simple so I'll close out of that and let's take another look at that script let's try to understand exactly what's going on here so at the very top of the script like always and this is probably going to be the last time I'll ever mention this we have the shebang at the top of the script as the very first thing again that lets our shell even if it's not bash understand which interpreter which shell we want to run the script under so that way we can help ensure that it actually does run within The Interpreter that we wanted to run under next what I'm doing here is I'm creating a variable and I am setting that equal to slash user slash bin slash h-top and that's the actual path to h-top if it was installed next I'm setting up an if statement I'm doing a file check against command the command variable and sends command equals an actual path that starts with a slash this is the path that H top would be found under then this is essentially the same as if I typed this it's just checking to see if that file is present I didn't have to use a variable but I did I'll change it back I just wanted to show you what that's doing if that statement is true what we want to do we want to do something right well what I want to do is Echo command is available since I'm referring to the name of the variable here it's just going to go ahead and print what that variable equals along with is available so what that will actually show is user bin h-top is available if it is and then let's run it now I could have actually included something here within the if statement to run htop but I didn't do that instead I just jumped right into else if it's not present what do I want to do well I want to let the user know the command is not available we're going to install it and that's just a simple Echo statement nothing special about that but let's take a look at this Command right here on Debian and Ubuntu systems and again if you're not running on Debian or Ubuntu don't worry about it it's perfectly fine I'll just explain what it's doing we're running first the sudo apt update command and with apt update is not actually going to update packages what update means in this context is it's going to synchronize with the mirror the repository to find out what packages are actually available this is something that you'll want to do once per day on a Debian or Ubuntu system when you're managing packages at least that just refreshes everything it's a good idea next we have two ampersands here but this allows us to do is chain commands together and what this means in particular is that if the First Command sudo apt update is successful and I need to underscore that if it's successful it's going to immediately run the second command if the First Command were to fail the second command is not going to execute when we have the two Hand percents so the First Command definitely needs to work before the second will execute so first it's going to re-synchronize then it's going to run sudo apt install h-top but it's going to do that with the dash y option Dash y means assume yes don't give me a confirmation prompt just go ahead and do it and why that's important is because when you are writing scripts you want to try to eliminate any prompts that you can you don't want the script to ask you questions because then you have to be in front of it answering those questions the whole point of a script is to automate something so if you're standing there answering questions well that's not really a great script is it it might be good and it might be useful but we just want this to run and another reason why we might want this to just run is if we are running this overnight or via a schedule I don't know about you but if this script needs to run at three in the morning then I'm not really interested in waking up at three in the morning just to answer a question that this script might be showing me I just want it to work I could check the results in the morning anyway next we're going to close out the if statement the entire point of the if statement is to check to see whether or not the command is available and if it's not to run the commands that are necessary to install it if you have a different distribution then you can replace the sudo apt update line and the rest of it with whatever is required on your distribution to install h-top I'll leave that up to you if that's something that you want to do but anyway we're closing out of the if statement and now we're out of the if statement at this point H top was either already installed where the script did install it next what I'm doing right here is I am simply referencing the variable no Echo nothing just a variable Now by using the variable name just like this it's the same thing as if I just typed slash user bin h-top on the command line because whatever this command variable is equal to and we set it equal to this that's what it's going to do so it's essentially the same as just running h-top now the cool thing about this is that if I wanted to check for a different package then I could go ahead and change it just like that now we do have a bit of redundancy right here with the name actually repeating itself not something that I should be doing we're going to let that slide for now we're still early in the series but the point is we have a script here it checks for the existence of something a package a command if you will and it will run it if it is present well either way it's going to run it but if it's not present it installs it first and then it runs it now this could be useful if you wanted to automate the running of a program but we're going to get into more complicated and awesome scripts later on so I think this is good enough for now now actually what I want to do is change this script I mentioned that this isn't very good right here and well it's not um what I want to do instead is just make this better so what I'm going to do is change command to h-top I basically just simplified it and I'm going to go down here I'm going to rename it here as well so now h-top is not hard coded anywhere what I want to do here is instead of doing a file check check this out I'm actually going to remove most of the statement here and in this place I'm going to type command Dash V dollar sign command so right here this is an actual command called command I know that's a little confusing but I'll explain it in a moment what I want to do right here is see whether or not this script runs whether or not it's actually going to execute let's save it I'll minimize it dot forward slash my script and it works there's nothing actually different as far as how it executes but I wrote it in a different way and let's bring up the script and what I'm going to do is help you guys understand this now first what I did was I changed the command variable to equal h-top instead of the fully qualified path to the command I instead just typed the command that still works but what's interesting is that in the if statement here I've removed the brackets brackets are actually only needed if you are running the test command even though we didn't actually type out the test command when we use brackets in an if statement we're using the test command but instead of actually using a test Commander brackets we're just using a normal command a command called command the command command actually checks for the existence of a command now it's a coincidence here that I named it the same I could have just named this I don't know program name for example it doesn't really matter if you do change this you want to change this everywhere this is a variable but this part right here is just a command the fact that they're named the same is purely coincidence command Dash V is something that we can execute on the command line so for example command Dash v h top and it gives us the command that means that it's present so we didn't really need to check for the existence of a file command is actually a command that specializes in letting you know whether or not a command is available that's why we used it whenever possible if we can use a built-in command we should probably go ahead and do that now the remainder of the script isn't really any different we just change the top Parts here the rest of it executed exactly as we had it before in this case command Dash V to check for the existence of a command is more appropriate so that's why we switched over to that and our script is actually a little bit more efficient now as an aside I mentioned earlier that I removed the brackets and I also refer to the test command now in each of the if statement examples that we've had up until now we were actually executing a test that was within brackets when you do that bash is assuming that you are using the test command even though we didn't actually type test it's using test in the background that's what the brackets do let's exit out of here now we have Man pages when it comes to Linux and actually this is beyond the scope of this series but it's something that you should probably be introduced to anyway we could check the man page for the test command we can see that we have the expression in Brackets just like we did in the if statement and it gives us all kinds of information here about the test command that goes way above and beyond what we're going over in this video but it even gives us the greater than or equal the less than or equal and so on we have the individual checks right here that we can use so if you wanted to find out what more you could test for within the brackets well here you go if you scroll down here there's all kinds of information that pertains to the test command so if you are curious how the test command works then you could check that page out by typing man test and find out for yourself so anyway that's why I've removed the brackets I'm no longer wanting to use the test command I just want to run a command and test whether or not something is present and that's exactly what it did now at this point what I'm going to do is stop this lesson right here because I want to jump into the next one and in that lesson we're going to talk about exit codes now there's a lot of information here about if statement so before you just hurry and run into the next lesson I recommend that you just spend some time with this play around with if statements make sure you understand it and then we'll continue foreign you know we're just moving right through this series and I hope you're enjoying it so far if you are enjoying this series then please click that like button that would really help me out anyway if you are ready to move on to the next lesson well it's already uploaded but don't move too fast you definitely want to make sure that you're taking your time to learn each of these Concepts before you move on to Future lessons but if you're ready then well I'm ready too so whenever you are ready then go ahead and meet me in the next video and I'll see you there [Music] thank you [Music]
Info
Channel: Learn Linux TV
Views: 30,915
Rating: undefined out of 5
Keywords: Linux, gnu/linux, LearnLinuxTV, Learn Linux TV, Learn Linux, Linux Training, Linux Tutorials, bash scripting, bash script, bash for beginners, shell scripting, linux shell, bash scripting tutorial for beginners, bash scripting tutorial, shell scripting linux, shell scripting tutorial for beginners, shell scripting tutorial, hacker, hackers, howto, how to, tutorial, guide, bash, bash scripting linux, bash scripting basics, shell scripting basics, linux for beginners 2022, if statement
Id: YrE1Qg-Aw0Q
Channel Id: undefined
Length: 31min 42sec (1902 seconds)
Published: Mon Nov 28 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.