Bash Scripting on Linux (The Complete Guide) Class 06 - Exit Codes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
thank you so here's a question for you guys when you run a command in bash then how do you know if it was successful or if it failed well I think the obvious answer here is that if you see an error message then I think it's well quite obvious that the command failed but how we actually determine success or failure in bash is not quite the same way in which we do that in real life there's also the concept of exit codes and what exit codes allow us to do is actually determine whether the command that we've just entered was successful or if it was not successful but in my opinion the best way to learn something is to see it in action so let's dive in and actually see exit codes in action and by the end of this video you'll actually understand exactly what they are let's go ahead and dive in foreign we're going to take a look at Exit codes exit codes help us determine whether or not a command was successful now to be fair we can often use common sense to determine when a command was successful so if I type ls-l against a directory then we could probably safely assume that this command in particular was successful I mean we did see results we didn't see an error message so the command was successful video over we're all set let's move on to the next lesson well actually it's not quite that simple yes that logic often does work out but according to bash whether or not a command was successful may or may not be the same as our understanding as human beings whether or not a command actually was indeed a success now similar to that if I run ls-l against another directory this time I'll choose the misc directory I'm getting an error message it's telling me that this particular directory does not exist now it doesn't take a computer scientist to know that the command failed I mean it's literally telling me right here that there was a problem so obviously there's some sort of error the command didn't work so I think we can be reasonably sure that this command was a failure but so far we've been determining whether a command was successful or not using nothing but our own judgment so how exactly does bash represent success or failure well for that bash provides us with a special variable that contains an exit code and we can view the exit code of the most recent command to see whether or not bash interprets that command as being a success or a failure and that's what the exit code actually does it lets us know whether or not a command was actually successful or if there was some sort of problem for example let's list the storage of the Etsy directory yet again and directly after that what I'll do is use Echo to print the contents of that special variable that I was telling you about which is actually dollar sign question mark and this variable believe it or not even though we didn't declare it it was already declared when we entered the previous command and this variable right here contains the status of whether or not that command is considered a success so I'll press enter and we get an exit code of zero but what does that mean well let's run a quick experiment what I'll do is list the storage of an invalid directory yet again and now let's check the exit code this time remember last time we received a zero so what does a failure look like well in this particular case it's showing 2 for the exit code so the First Command which worked gave us an exit code of zero the failed command gives us a different number so what exactly does that mean that's actually the easiest part of this entire lesson I could summarize the difference in a single sentence an exit code of 0 means that the command was successful and an exit code of anything other than zero constitute's failure the First Command ls-l against the Etsy directory worked just fine it gave us the results that we were looking for and we especially know the command worked because the exit code was Zero the second command gave us two which is not zero so that means that command in particular was not successful however why do we need to know what an exacode is I mean it's pretty obvious when something fails right if we get an error message the command failed if not that means the command is successful well the issue is that when we write scripts we write them such that they can run by themselves without us needing to watch them normally scripts run on a schedule for example a backup script that kicks off at midnight every night in that case I'm assuming we'd rather not wake up at midnight to make sure that the script executes properly so basically with an exit code we could check for a non-zero exit code and take action with the backup script example that I just came up with if that fails it'll exit without the exit code being zero then something can run right after that such as well a command to email the system administrator maybe that's you and let them know that something went wrong maybe in your case it's perfectly acceptable to go ahead and check the following morning if something was a success or not and if you see that something failed like an email in your inbox with an error message then when you get into the office or you connect to the office you could go ahead and fix the problem now let's see some script examples that utilize an exit code in some way and here we have the script that we've been working with I'll go ahead and empty it out so what I'll do is create a variable I'll name it package I'll set it equal to h-top and then what I'll do is type sudo apt install and then the name of the package after that what I'll do is type Echo and then I'll say the exit code for the package install is and then dollar sign question mark just like that so I'll save the script and exit out and what I'll do is actually remove h-top from my system otherwise I mean the script isn't going to have anything to install I'm telling you to install h-top it's already installed so I'll just go ahead and remove it so we'll finish that and let's run the script now it went ahead and installed h-top for us but pay special attention to this last line right here this here is what I echoed I also echoed the contents of the dollar sign question mark variable that if you recall contains the exit code and the exit code is zero that's great that means that the command within the script that we're checking was a success and with this script we can start to see the value of exit codes like I mentioned earlier if something was to fail maybe you want some sort of action to be taken I used an example of email but maybe you might want a log file to be updated that you'll check later or some other action to happen as a result of failure now just to make sure that the script is actually working as well as I think it is let's bring it back up and I will change the name of the package to something completely different I'll change the name to something that doesn't exist there's no package named not exist so I'll save it let's go ahead and run it and the exit code this time was 100 it's not zero so that's a failure even though I made that failure happen on purpose you could probably see why exit codes are going to be valuable in the future so let's go ahead and update our script so that way it's able to better utilize the exit code and that'll also be yet another example of why exit codes are actually a good thing so I'll change this back to h-top and I'll leave this line alone right here and I will delete this one let's go ahead and start a new if statement right here so I'm going to check the dollar sign question mark variable the exit code I'm going to see whether or not that equals zero then what do I want it to do if it does in fact equal zero well what I'm going to do is Echo something the installation of package was successful then what I'll do is type Echo again the new command is available here then we'll use the which command against package that'll show exactly where that particular command is located the fully qualified command but that's all well and good though I think we should probably do something if it's not successful so what I'll do is type else now with else if the exit code does not equal zero then we want to do something else hence else we're going to print package failed to install so I'll save it let's remove htop and let's run the script and we can see that it did in fact install h-top and then at the end it's printing the statements here that were associated with the success the installation of h-top was successful the new command is available here and then it executes which H top which gives us the path the fully qualified path to the command so that part worked just fine foreign test this I will change this yet again to not exist and let's try this again not exist fail to install well of course it failed to install there's no such package but you get the idea this particular script is actually taking the exit code into account here if it's equal to zero which again means that the command was successful it's going to tell us that and then it's going to give us the path to the command but if for some reason that failed it's going to let us know that it failed now obviously the output of the APT install command I mean that actually absolutely failed it doesn't take a rocket scientist to know that but this was just an example of how we can make this script do something different depending on what the exit code was of the command so what I'm going to do now is change this script to make it a bit more realistic basically more like a real script that you would actually find on a real Linux system again it's not going to be the most useful script in the world but we're getting closer and closer and we're definitely getting closer with this example when I change it so I'll go ahead and do that so right here at the very end of this line what I'm going to do is type 2 greater than symbols and I'm going to type a file name here and you can name this whatever you'd like it doesn't matter at all I'm just going to create a file named package underscore install underscore results.log now notice here that I have two greater than symbols this is a redirect this is something that we'll be using as we get further and further into the series but this is the first time that you've seen it in this series so rather than print all of the information on the screen showing the process of the package being installed what I want to do instead is redirect that output into a file the two greater than symbols what that's going to do is append the output of a command and send that output into a file so when we run this command we should find this file right here I will also change the package name back to h-top and then what I'm going to do I'll add two greater than symbols here as well and I will create a sort of failure log for this particular script it is just going to send this message right here into that file so if this works nothing should be printed on the screen other than what I'm telling it to print right here so that way we won't see the wall of text scroll by when we run this now assuming I didn't make any errors this should work just fine first of all I will again uninstall age top and you could use whatever package name you want to it doesn't really matter but let's run the script and see what happens hopefully I didn't make any errors we can ignore this warning right here that's just from apt but it's telling us that the installation of h-top was successful and the command is available right here so we see a lot less output here than we saw the first time and check this out we have package install results.log if I was to cat that out that's all the output that I would have seen if I didn't redirect the output of Apt install into a file I did so all of this is in the file but this just helped us actually clean up the output a bit so we don't see a wall of text we see mainly only what we need to see so similarly what I'm going to do just like last time we want to make sure that we test all of the scripts that we write so I'll change the package to something invalid again let's exit out of here and run it now right here it's telling me that it's unable to locate the package but the interesting thing is that I redirected output to a file so why am I still seeing this we'll cover that later in the series so what I would do is just completely ignore that for now there's a perfectly valid reason why that's the case we will get to that but let's go ahead and list the storage we now have the package install failure log file here and is telling me the name of the package which I made invalid on purpose failed to install just like we expected now what I want to do is show you guys a very important example when it comes to exit codes because this is something in the real world that might actually bite you and frustrate you and I want to get this out of the way right now so this is really important so what I'm going to do is create a brand new version of our script and I'm going to clear it out and what I'll do is create a variable named directory in my case I will set that equal to slash Etsy just like that I'll start the if statement and I'll check for the existence of a directory that's what Dash D is right there and I'm checking for a directory I'm just going to use the variable name right here let's close out the test we'll type then we'll Echo the directory and then the variable exists else if that's not the case we'll Echo a different statement the directory and the variable name doesn't exist okay so far so good now the last line in this particular script will be yet another Echo statement the exit code for this script in this particular run of the script is and let's print the exit code right here so let's save the file and exit out and run the script a directory slash Etsy exists the exit code for this script run is zero so at first glance everything seems to be perfect we have a script that's checking for the existence of a directory the directory that we're checking the existence of it does exist so this is not lying to us and it's telling me that the exit code for this particular script run is zero well that makes sense I mean the directory is there we know that it's there in fact I could prove it by typing manually ls-l Etsy it worked so so far we might be under the impression that this script is fine but it's not do you know why this script is wrong I'll give you a moment to think about it you could pause the video if you want some more time to think about it but whenever you're ready we'll go ahead and continue okay so let's continue so here's the script again and what I'm going to do is change the directory to slash not exist I want to force a failure here so we definitely shouldn't get an x equal to zero let's save the script and let's run it and see what happens the directory not exist doesn't exist the exit code for the script run is zero but wait a minute an exit code of 0 means success but this wasn't successful what's going on here let's go ahead and edit the script again and see if we can spot where the air actually is so here we have the statement that the exit code for the script run is and it shows the exit code which we got a zero for some reason let's go ahead and just test this out and what I want to do is type right here Echo and dollar sign question mark I'll do the same thing here as well and let's see what happens now immediately we see an exit code here of one that is an unsuccessful exit code but by the time we get down here the exit code is now zero why is that well here's why so what I'll do is just take out these extra Echo statements return the script back to what it was even though the check right here where it's checking to see whether or not this directory is present in this case I set it to not exist so right here the exit code is not going to be zero this was not a successful test now right here this Echo statement this is successful it was actually able to Echo something so this statement no matter what is always going to have an exit code of zero it was able to Echo that worked so exit code 0. if the directory doesn't exist it's going to move down here to else and it's going to Echo to let us know that the directory doesn't exist but that Echo was successful even though it's telling us that there was an error it was successfully able to Echo to our terminal so that is also going to get an exit code of zero that's why when I put an exit code above the echo statement that's where the exit code actually matters not after the echo statements those Echo statements are fine they're going to run but if we check it before the next command runs then we're going to see the real exit code and that's why we were able to get a different exit code but at the end of the script we get an exit code of 0 because the echo statements will run just fine so the moral of the story here is that when you want to differentiate what happens in a script based on the exit code you'll need to make sure that you're checking the exit code at the most appropriate time definitely do some extra testing anytime you're utilizing the exit code in this way when you're checking for something you'll definitely want to make sure that you simulate an error so make an error happen on purpose and then you could test to see whether or not the script behaves appropriately but there's actually another way that we can handle this situation so what I'm going to do is write a different script and what I'm going to illustrate is that you have control over what the exit code ends up being so yet again let's clear out the script and start from scratch so I'll type Echo I'll type hello world and right after that just like we've seen I will Echo the actual exit code which should always be zero so it shows hello world and zero exactly what we were thinking was going to happen now what I'm going to do right after hello world is I'm going to type exit and then number one so this is going to be interesting what this is going to do is force the exit code to be one no matter what so I'll save it yet again let's run it and it only prints hello world it didn't actually print the exit code okay that's interesting let's go ahead and just check the exit code manually just like we've done before the exit code is 1. okay well so far so good right so what I'll do here is exit 199. I just make it totally stand out so minimize that let's run it and the exit code is exactly what we told it we wanted the exit code to be so similar to that what we could do if I bring that up yet again I'll just go ahead and run sudo apt install not exist we'll set the exit code to 0 right here let's save the file and run the script again we're just playing around with exit codes here that's a good thing to do that's how you learn unable to install package not exist well we have a successful exit code here well we force that along so if I bring up the script again right here I'm typing exit 0. now what exit will do is exit the script with whatever exit code you actually type here and that's why this line never runs this line right here is actually supposed to give us the exit code but it never does that because this line right here it actually exits out of the script Nothing else will be run no matter what we type here it's done on that second line of the script it's going to exit it's going to exit within exit code of zero that's it so this statement right here will never run let's go ahead and change this up a bit and for the next script what I'm going to do is set the directory back to Etsy just like it was before so if we're going to test to see whether or not that directory exists then we'll Echo and here we're going to force an exit code of one and we'll just Echo another statement right here and then I'll add another Echo statement why not and another so there we go basically the previous version of the script I just added a bunch of different things here for example I'm going to set the exit code to what I want it to be within the if statement and then I have some statements down here at the bottom and I think you probably know exactly what's going to happen here but let's find out the directory slash Etsy exists well we know it does right so if I bring up the script again notice that these three statements didn't run even though I had exit within the if statement and I have it in both sections underneath then as well as else that's going to exit the entire script it doesn't matter that the exit is within an if statement exit means exit it's going to absolutely exit that doesn't mean it's going to break out of the if statement and then continue to run the other Echo statements that are down here at the bottom exit like I said means exactly that it's going to exit out and we don't actually have to give it an exit code we could just simply exit but what I like to do is give an exit code within the if statement so that way I have actual control as the creator of the scripts what the exit codes are and what they mean so I could create an exit code of 199 if I wanted to and then I could look for that specific exit code I have full control over this which is what this allows us to do so with exit codes we're given more control over our scripts and we could actually create the scenario that we want to check for so if it gets down here to else it's only going to get down here if there's a problem that's the only scenario that's going to create this particular outcome so I want to give it exit code 199 because maybe this particular section of the script 199 has special meaning to me and now I can make that whatever I'd like again we'll understand this better as we get further into the course but for right now that was a lot [Music] so there you go yet another video in this series is all set and I hope you're not moving along too fast through the series but in this video I taught you guys exit codes it's a very important topic and hope it helped you out if it did then please click that like button as always to let YouTube know that I helped you out and I'll see you in the next video which is actually already uploaded so I'll see you there [Music] thank you thank you
Info
Channel: Learn Linux TV
Views: 21,420
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
Id: 6N4RNPRx0xs
Channel Id: undefined
Length: 27min 14sec (1634 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.