Introduction to Bash Scripting | Eric Simard | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Introduction to Bash Scripting

teacher avatar Eric Simard, Join us on FB

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

22 Lessons (1h 2m)
    • 1. Intro

    • 2. About

    • 3. Special characters

    • 4. Bash variables

    • 5. Functions

    • 6. Function return

    • 7. Declare statement

    • 8. If statement

    • 9. If test on files

    • 10. Binary comparison

    • 11. If with brackets

    • 12. For Loop

    • 13. While & Until loop

    • 14. Input redirection

    • 15. Break & Continue

    • 16. Command Lines arguments

    • 17. Linux style args Part 1 (Space separated)

    • 18. Linux style args Part 2 (= separated)

    • 19. Linux style args Part 3.1 (getopts)

    • 20. Linux style args Part 3.2 (getopts error)

    • 21. Create menus with SELECT

    • 22. The project

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

In this class we start learning Bash scripting. No previous programming knowledge is required.

I expect you will have questions and require clarification, head over to our facebook group: Learning Linux

I deliver this class in a unique format. Look at the attached file in Class Project, you will see a
This is the only file you need. It contains all the information you need and examples are integrated into it.
If you are new to emacs and org mode head overĀ here and watch Why learn emacs and Install Org Mode

Video lessons goes as follow:

  1. Quick introduction
  2. About
    Why did I choose to deliver this class with org
  3. Special character
    We cover Comments, command separator and the difference between single and double quote.
  4. Bash variable
    How do we declare and use variable
  5. Functions
    How do we declare and call functions. Including passing arguments to functions.
  6. Functions return
    What can be return from a function.
  7. Declare statement
    We look into the details of the declare statement.
  8. If statement
    Here we first look at the if statement, its structure and some example.
  9. If test on file
    Now we look at using the if statement to make some test on files, Does the file exists? Is it a directory? We quickly look through the full list of test that can be performed on files.
    It help to follow this video if you have a clear understanding of what files are in Linux. For more details head over HERE for a short class on the subject.
  10. Next we look at more common way of doing test, ( < > <= ... ) but also how the test works with different types of brackets.
  11. For loops
  12. While and Until loops
  13. Input redirection
    A loop can be control by redirecting the input from a file or another process.
  14. Break & Continue
    Here we have a look at the break and continue and their different behavior depending on the loop.
  15. Command line arguments.
    first look at parsing command line argument to your scripts.
  16. How to implement Linux Style arguments in your scripts
    There are 3 common ways of doing so:
    1. Space separated
    2. = separated
    3. with getopts ( 2 Parts video, usage & errors)
  17. How to create menus with SELECT builtin.
  18. The Project

Meet Your Teacher

Teacher Profile Image

Eric Simard

Join us on FB


Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Intro: Hello and welcome to disclose here. Why I want to teach you about bash scripting. My name is Eric Samara. I'm 36 years old. I have approximately 20 years experience running an operating Lennox. And why would you want to do to learn how to do bash scripting while very simple everything that you do on your computer. My big majority of it can be done on the command line. Whatever can be done on the command line can be scripted. You can create yourself many script to assist yourself in your daily in your daily tasks. So without any further waiting, let's learn how to script. 2. About Okay, let's talk about that org's file here for a quick second. The reason why I do this is because organ mode add so much functionality to a simple text file that it will greatly enhance your take away from this cost. You will walk away with the class with a single file containing all your notes that you want to take in everything. That all the information I wanted to transfer to reference the exercise, all of that inside of a text file. So if you don't have the Mac an organ mode and stall, I invite you to go to the free limit's been video number 14 will walk you through the process and see you in the next house. 3. Special characters: Okay, well, let's get started. Would bash scripting first. I want to go over which you, uh over the term of a few special characters that start with simple out to add comments to a bass script while in a bash script alliance. Starting with this character is a comment. For example, this would be a useless crib because it does nothing. It just has a comment on it. It can also follow the end of a command. But you need to have a space in between the end of your command and a command sign. Otherwise it will, through an error bash will also allow you to place comments embedded within a pipe, for example, and in a lot of other areas, that makes it very hard to read. Second special character I want to go through which you is a commend separator de semi column allows you to put more than one command on the same line. So, for example, this one here echo ello and that echo they're all on the same line. So if I was to remove the results here and I go here and I press control C control, see, confirm that I want to evaluate the coat. I have my results back here. I also know that normal other commend separation and Olynyk Shell also works in a bash script for example, this one which forks a, um, process in the background and then start the process that comes after. You can also use that into a script to ah and double one here, which means that the second command is run. If the first commend this successful can also be put in a bash script. So what's the difference in between double quotes and single quotes? The difference is that double quote will preserve most special character from interpretation, while single quote well preserved, all the special characters. I'll begin here with an example of no quotes in a command line and the double quotes. So in this first line here, this will list all the file in slash var slash log that starts with s why and has anything else after, while the 2nd 1 here is going to look for the file read and s why with a star at the n. So if I had control C control, see to evaluate the code my first command list might file while my 2nd 1 tells me that there is no file s. Why star in this example here I demonstrate the difference in interpretation from double quotes to single quotes. So I have a variable called bar which contains the string help. So if I echo like this, you can see in the results down here echoes Hello. It is a proper way to written, but it is a good habit to quote your variable either way, so double quote echoes the value of our while. The single quote equal prints out literally dollar var. So just to show the example, if I erase the results and I come here and I had control see twice I see the result of my command line right there. So that is it for the simple special character that you have to remember for now. In the next session, we're going to start looking more into variable and functions 4. Bash variables: Now let's look into variable in bash. Variables are untied. Basically, what that means is that underneath the hood they are all character string. Except if you're variable contains only digit bash will allow you to do our admitted cooperation on it. See to read me to know how I'm going to open that code section here because I want it in full buffer. So here I declare a variable eight. It is a good Abbott, but it's not required. I assigned a string and I create an assign variable. Beat the number two I echo them. Then I go around and I changed eight to number four and beat to a string. I echo them. Once I'm here, I create the variable scene and I assigned it the result of a plus two, which is currently allowed because it contains only digits. Then I attempt to do the same thing. I create variable D and I attempt to assign it B plus three, except beat is a string. It is not a digit right now, so let's see the results of that. So if I had control C control scene, then you can see the results here and you can see the error where bash complain about attempting to do in arithmetic operation on the string and the result of that variable. So this is the quickened basics of how variable work. We're going to see them more in detail when we enter to declare or typeset the section in the next session, we are going to look into functions. 5. Functions: Now let's look at functions, the basics of it declaring a function and passing it parameters functions or declare with the function. Keyword example. Function my funk after the function named. There needs to be a space, and after that you can open the function content with the brackets, but you need to have a space in between. You can put those brackets here in between, except nothing can go into it. So it's useful if you have the habit of doing it for, Let's say, C programmers. But Bash does not take arguments in this way. You're not allowed to put anything inside of it. So let's look at the first section of code here that I've got. I forgot to mention something very important at the beginning of this class. This line here is what we call the she bang, and she needs to be there. This is the path to de shell interpreter or interpreter that is going to interpret your script because we are working in bash, scripting the first line of every bash. Script needs to be this, um, so let's get back to the function. So as you see, I declare a function I need to have a space. If there is no space bash will complain about it now. Dysfunction here. What it does that first will echoed that you have called a function. Then it will test to see if the perimeter one a zero in linked If it is, that means you did not pass any parameters. Otherwise it will display you the parameters. This is how you access the arguments were a function number one, number two number three and they are space separated. So this is the same thing except using those brackets here. Like I said, it is not needed. But if you have a habit of putting dem, leave them there. If your c programmer, you're going to like it. So let's execute disco Dhere control C control sea whips. There we go and you can see the result of that function here. So once again, I invite you to go in there, mess around with things, changed them, break them And in the next session we are going to look at how what can be returned from a bash function 6. Function return: Okay, What could be returned from a function in bash? Simply put an integer Onley Any attempt to return otherwise will result in a nearer. So in disco the Skoda here that I've got I've got the exact same function I had before except by either returned a zero or one. I then created a function called check red valve for check return value and in here. And this will make more sense when we go through dia. If statements check that the first parameters that first argument that the function receive If it is above zero, that means that we got an error. If it otherwise it means success. So we first call on my function and then we called or function to take the return value. Whenever you need to check the return value of your last run command and bash, you excess it with you, access it with the dollar question mark sign. So you run a command, it will return a value zero or one or more in order to check that that value is stored in the variable. It's a special variable star dollar site. So we do that again would check my function with a parameter and then same thing with the other ones here. So if we look if we executed with control C control see, you can see it. Though you have called you have not given me a parameter return Number one function returned one. So this is how you return value from a function. So what if you need to return the string? Well, you can't return the string, but you can, in a sense, passed a variable by reference and modified at variable from within the script itself. So if let's say you need to return a value, you have to actually change a variable outside the functions cope while wooden That's cool . So here I declare var I make a function Rev are which will evil and we'll put into its first parameter. It will put what I put here. So if I look here, I declare my function. I assigned a load my variable var I go with I called the function and I passed my variable of our but notice There is no dollar sign here before, Otherwise it won't work. And then after I go with the string, var will have changed for L. A world. So if I goes that and I run it, you can see that it is echoed before it is sent to. Rev are an equal after so you can't return anything else but an integer from a bash function. But you can use passing a variable by reference in order to change some variable, and the next session we are going to look at, declare and typeset and look into a little bit more into variables. 7. Declare statement: OK, now let's look more in detail into the declare statement. You've seen me use it in an example just a few minutes ago, declare a typeset. They are both the same. Declare a specific version. Two of bash and typeset works on other shell like a sausage declare comes with options, and we're going to look at him here. The dash, Our option is read only. It's a rough equivalents to the sea. Constant type. Any attempt to change the value will result in errors. So if I look at the script here, I declare, read only our ove r and I said it to two. I echoed a variable. Then I attempt to change it and I echo the variable again. I will remove the last results. Rerun the script, and you can see the variable remained the same and bash through an error when we attended to change it, you can use declare to declare integer uh, with the dash I option. So if I declare one here my end, I assign it to I echo it. Then I attempt to change it to a string with spaces and and I echo my end again. And as you can see bash here throws an error and the variable remain at number two. Then I tried to change it to a string with no spaces in it. And bash does not complain, but my and equal zeros. The point is, if you declare a specific integer, make sure it remains a specific integral. Otherwise, just don't specify that's what you want. You will have less restriction where you will be able to change it back for good measure. I'm going to remove the results here and we run the script and we have the same results now to declare a Neri with bashes the dash pay option. So here I declare my Eri I initialized the area. They are space separated Here I use a for loop which will will see in more details to go through each element inside the area itself and I echo them. I do it in another way, using a while loop and I actually do in arithmetic operation in this case here. So those two we will see in more detail further down the road. But if we do it now, you can see it going through the area and giving me to some of the example, you can also declare specifically a function. Now. If you do declare f widow argument, it does a listing of all the function that were previously defined within that script. So here I declare my function and I specify debt. It is a function with the option dash F. Then I declare variable my funk, Torri. But I don't say what it is this function I did not declare and that is not a problem. This is the function to definition that I declared previously. And now I've just designed a variable of function. So my funk three is now a function. I called them 123 and then I used to declare Dash F without options. Let's see the results. You've called one you've called to. You've called three and then it list all the functions itself. In the script, the dash exits for exports. I listed here because if you look at the options on your own, you will see it is there. This I will describe later. It will make a lot more a lot more sense when we have a better understanding of the bash environment and its export functions. and now, by itself. All we've seen that previously can even try it in your shell in your terminal itself. Just right, declaring You'll see it'll print you out a bunch of information. It's good to look. So in the next session we are going to start looking at conditional statement, including the if statement in the case statement. 8. If statement: Let's start looking at conditional statesman's conditional statement. Its first look at the if statement You have a reference as usual here. Let's have a look at the structure. All make that in one buffer, so it's easier you can put in if statement in a one line like this. If your test commend would be here, then you would need a semi column. The space is important. Den Your code to be executed. Same thing with the semi Colin in the spaces. So that would be an if statement on the one line if you can make it. Compacted brackets are not always required, but it's a good habit, but you can put it in a multi line like this. If your test sequence here semi column important and so is the space, you can use it with single brackets or double brackets. You will see and understand why a little bit further down. What? This is how you do if you want to add an else statement if semi column den ales and finish with f you and this is how you would do your if else if an else statement, So notice that the else if also requires a semi column and then keyword. And, as always, spaces are important. So what is the difference in between the single brackets in the double brackets? And here we have a nice, good little script. This is a copy and paste from the source written there. So contrary to the single brackets, double brackets prevent word splitting of variable values. So if R is equal at bar with spaces, you do not need to double quote var in a test, even though it remains a good habit. Also, the double brackets prevents path name expansion so literal string with wild card. Do not try to expend to filing. Remember our Except Remember, for example, with the LS file at the beginning, using double brackets, double equal and ah negative equal interpret string to the right as shell glub pattern to be matched against the value to the left, for instance, value equals valve. Okay, let's have a look at this script here. Here's what I've done. I created my value of R one and R two, which are the same. And then I according here, I echoed the test, and I used the quote, single quote and double quote in such a way that it will display exactly what is displayed in the in the test section here. And then you have the results. So I have the single brackets with Div are in double quotes single back it with the variable with no quote. Double bracket would double quotes, double Dracut with no quotes and then a different type of equal sign putting to equal signs instead of one putting same thing here to equal sign one bracket, no quotes and so on. So if we execute disc owed, you can nicely see the results here. And there will be a good example of how to use single and double quote and what difference it simply makes by having single or double brackets here. So you see that when we do the equal like this var one Anvar to are equal it matched when we did it Like this bar want Anvar to are not equal, it doesn't add up in the double quotes with the double brackets they're equal to double quote double brackets with no quotes They are equal and same thing here dis matches This does not equate and those are equal and so are those. So that gives you a good example of different behaviour, depending on double quotes, double brackets, single brackets. I highly invites you to get inside death script and play around with it. Change it, modify it, break it at them. Different tests. Ah, we will Seymour into the possible test that can be done in the next section here. 9. If test on files: Okay. Now, let's see what kind of tests we can do. Own files under links for a full list of test that you can do on files. Follow the link that is right above here. We will go over it quickly together after this, But let me first remove the results. Here. Let's see what we got here. I got a few example. Uh, so here we start defining a file into a variable. And now I test to see with the option Dash eight. If the file exists, notice that in the if statement single brackets are used and as usual, spaces are important. Now, here I show you a negative test. This is a file that does not exist. So if the file does not exist, we go this loop otherwise, because this loop now, I reset the file Desist, love. And then I checked to see if the file exists. And then I checked to see if the file is not a directory. So let's close this and you can see the results right there that my viruses like exists. This one does not. And this one is a regular file, and it is not a directory Now let's have a quick look here at the details because there's quite a extensive list of option you can do. Eso, for example, this one we've seen to see if the file exist that will equate to true, even if it is a directory. Because under Lennix, a directory is just a file that has the property of holding other files. Does oneness to know if it is a block special device? A correct character. Special file. Sorry Block Special file and director special files for more detail on that, you can see my costs on the in Lenox. Everything is a file. I provide a very good explanation of what we mean by this a dash DS to know if it's a directory. Dashi is the same as that, eh? Uh, afternoon. It's a regular file. So not a directory, not a symbolic link, Not a block special or any of that. Just a plain regular file. Uh, this is spin off its symbolic link. As you can see, there is quite some extensive one even up to the point that in this the test here, it's true. File one has been changed more recently than filed. Do or a file one exists and fall to it does not. So you can see there is a pretty long list of extensive tests you can do on files within the if statement in the bash script eso I invite you to go through and modify that pieces of code there, uh, see what kind of tests you can do on your own file system. 10. Binary comparison: OK, now let's look at comparison operators. Once again, you have the reference here which we will. We will go through to get her quickly at the end. I first want to show you some bash specific operator. This creates a binary comparison and they are to be used with Onley integers I do display in the script What happens if you use it with a string string uses different sets of ah, comfort comparison operators. So let's look here. I set up three variable ABC A and B equals one c equals two and I echo the information here and I used a single quote to make sure that this echoes dollar A and not value inside of dollar eight. Uh, now let's start going through the test that we accomplish here. So in this case here, we check to see if dollar A is equal to dollar beat. And once again, I echo using the single and double quote wherever needed, so that in the result, you see the test that's been performed and the results that you got So this one here is not equal. This ah operator is greater than greater or equal lower than lower or equal. Then I proceed to set my variable A and B to a string a word. Hello? Hello. They are They should result in being equal. Except you will see in the example. And those are not to be used for strength. So let's close this up here. But that's run the results. So we have the variable, and now you can see the test and the result that we got. Now, this is when we attempted to, uh, compared two strings. This is the error that bash has given us because it was expecting an integer expression instead. And that results in not being equal, even though the two strings were actually the same. Now let's look at what it looks like. If we are to use double brackets instead of single brackets, it works the same weight as long as you're using integers Ah, to perform to comparison now it will work different here once I change it to string. See that A and B do not equals okay, and I run the same comparison here, but would double brackets let's see the results quickly. First of all, it does not given error, but it's telling me that a is equal to be in my strings even though they are not equal. Eso remembered at those comparison. They are binary comparison operator, and they are to be used for integers on Lee. In the next session, we look at more common ways to do some testing. 11. If with brackets: OK, now let's look at more common ways to test Uh, that's wicked denotes here, first of all. Ah, a little warning. More common ways to test means more ways to get confused on how things work. Bashes an ugly language to play with. Very strong, very powerful but very ugly. So first, we're gonna look at the difference in the if statement using single brackets Dan using double square brackets and then using double brackets like this the result of the following three scripts can be a little confusing. What's important to notice and remember is that single bracket if test works good to check if integers or equal or double equal, this doesn't work very good in single bracket point being single brackets are good for equals or nothing at all. Single brackets are not reliable to see the least when comparing with those operator by the re operators works fine in single brackets by enemy operators is the one we just saw. So let's have a quick look here at the code for integer comparison with single brackets. So what I did in those coat is that I set up variable aid, be in C and then I have written the current test, and I've used a bracket. And I've written that the string in the way that it will reflect exactly what is written here and the minus end tells Echo to not put a new line at the end so that this or dis line well, echo at the end of at the end of the 1st 1 And I've also added as if the results were either right or wrong. So if we close, let's go look down here. Yes, let's go, cause that turned the results so you can see you got this one right? This one, right. This one they got wrong, this one they got wrong. This one they got wrong. This one tour in error. Ah, and so on. So, like I was saying, the single brackets are only good for those two signs here or the binary operator we've seen in the past. So it might be easier to just remember to use a single bracket for battery operators. That's look at its cause. Those results now what? Double brackets. So here I have done the same thing. Echoed the current desde away it is written, and if you notice that there's two here that I'm not putting in this case because they don't work. So let's run the result of that. And as you can see that already better it is getting all of them right now, if you've noticed those two here when you look at the first example in the second or actually missing in the second example, they work slightly different. Previous operators can also be used in the same way. Now we use we do the test using those counter brackets and then I re attempt test mentioned in under example. You can see they got it right now we attempt previous tests with this. This causes Americans and attempts an assignment. But this works proper, dissed works proper. This doesn't work proper because it attempts and assignments in between a equal be and this is good. This is good. So as you can see, the if statement with those bracket offers results of their more like other language where a simple equal sign will basically given assignment. Is that testing to see if they are equal? Eso you? The just of it is that you are better off to use those counter brackets and your if statements and then you the single brackets for binary operators in next session here. And you hope Sorry. And you can see in the short here when doing binary operator used single brackets and use those bracket to do any other kind of operation. Always a good habit to quote your variable in the next session, we're going to look at string comparison. 12. For Loop: Okay, Now let's start looking into loops. The 1st 1 that I want to look what through is the for love? Once again, you have a link to documentation here. Uh, the structure of the four group is very simple. Four items in less do. So it's a bit of the same structure as the if statement here, we have an example of a four loop going through an area. Look at the code here, which you So I declare an area which is based separated of simply number. So four item in. And this is, ah, the format to basically tell bash to use all the items in the area. Uh, do echo item. So that's a very, very simple example. And as you would expect that list every item in the for loop here, I use a for loop to go through the argument supplied on the command line. Let's say how you would go through the argument that you put when you call the script. So this is the format to get the number of argument that has been passed to descript. If it's equal to zero, we basically have an error except cold one. Otherwise, we print out the number of arguments, and we go through it now with, um, organ mode. Basically the header column command line and everything is space. Separated is being added to the command line whips. So there we go. Argument length is three and three Argument that I passed through. Ah, if you missed that this year is to redirect the standard error into the standard output so that when we evaluate with an organ, if there's an error, princip and the result instead of opening and you buffer. But now I can try with no argument here by removing them and you can see a supply, a Serie of argument. So this is the simplicity of a for loop. In the next little session, I'll go through the wild with you. 13. While & Until loop: Now let's quickly look at the wild loop. Same thing you have a link to, Ah, more extended documentation in the example here I used a while loop to go through a Neri eso. Same thing. I declared the same variable here. Then I initialize a variable to zero. I go get delinked a number of item in the area itself. I equity and for good measure. And then it is simply a while. X is Bill O Arlen, which is the number of items in the area echoes it. And if you want to do a increment ation in bash, you have to put it in between those two brackets. Ah, it is basically any arithmetic Operation on digits has to be put within those brackets. Now I'm using the same loop here, but to go back make a bit of a reference. And the way the if statement was working with the bracket and binary operation and common operator. So the while loop is the same here. You see that in order to use that symbol, I use double brackets. I can use the same thing as any of statements, single bracket and use a binary operator to do it, too. Let's quickly run it just for the fun of it, and it prints out to results, as we were expecting. Let's quickly have a look at the until loop. It is very similar to the wild loop, except that it will execute until the test results. True. Ah, instead of while the test results false or truth in the other sense. Anyway, eso I do the same thing. I declare an airy. I get the number of items except that until X is equal at the number of items in the area, I do toe loop on the inside. Same thing to increment x two. Let's run it just for good example. There we go. It runs it as we were expecting it. 14. Input redirection: OK, now let's look at input output, redirection and loops. Ah, if you know nothing about input and output of a direction, I recommend you head over to discuss here file descriptors, socket redirection and process substitution. It's explained in detail there. Um, here is a link for reference, as usual. Uh, another way to control loop is by specifying filed to reedy input from usually the command read is used for this as long as input or fed into the loop. It continues when it stops coming in the loop quits. This allows for some pretty nifty script. When you combine this knowledge with a good understanding of file type file descriptor and socket, you can control Alou by feeding data from a file on a remote computer. Um, this section here is if you press control C control Z to evaluate it, it will print you toe help manual for the read option right within your orig file. Ok, now, let's look at the code in this section here, So I first defined declare variable and assigned it the value to a path for file name that does not exist. I didn't create the file with the command touch. Then I proceed to issue a fine command on the root directory. I do this because it is guaranteed to give ah, standard error and standard output. Would that given commend? Because some folder I don't have permission to access eso. What's happening here is that I redirect the standard output into a file, and then I proceed to redirect the standard error into the standard output feed, which goes into a file I set allowed line count to zero, and then I start my Wall Command while loop were to read command on it. And all that Luke does is that it increments the line camp. This is the input redirection happening here. I put that symbol and the name of the file and read will read line by line that followed it until it is empty. Once that's done, it will print out or line camp. Then I clean up. We also don't need to create a pot we can create. We can use process substitution that's also describe in more detail in the class I showed you earlier, so we said the line count to zero the while loop remains the same, we start our input redirection. But instead of giving it a file name, we give it a process substitution, and that will give the same results. Now, let's see the results of that command. If you run the fine command for the first time, it can take quite a while before the results show up. Me. It's because the search have been have been cashed. Okay, so I got the two information here. And if I want do, maybe you can find out why the line numbers are not the same. 15. Break & Continue: good morning. Let's quickly finish our loop section here. We're going to finish this up with explanation of the commend break and continue eso as usually have a reference link. Great Here let's first look at a break Command. It is used to stop a little before it's normal. Ending eso it's looking to code here quickly disco Dhere You want to export it Not evaluated because it require user input. So I declare function person process come in And from there articular variable and my place All the command that is going to be received as argument into the variable cmd And then I evaluated and I returned to return value eso here. If you enter anything, it will call the PERL says command with the input that you've given If we receive a return value above zero, we echo an error. If you enter quit. We demonstrate the break command here So I will export that code by pressing control you control C control vnt and from there I am able to do there we go Or if I just put ls it imports it transfer all the commands that I am actually giving it. And if I put quit ad breaks. Dilute quickly. Let's look at to continue command here to continue a statement, resume it aeration for for a while and until loop They also act the same for a select lupin which will be seen later. If you use it in a for loop to controlling variable Take the value of the next element in the list when you use it in a while or until loop it resume with the same loop. It wasn't so. I'll give an example here. This is a continue command used in a for loop. So I declare in Eri I go through it if x ends up being position number three This is when we send continue command and otherwise it is X equals X old is normal. You're going to see the Lupul finish? What do you mean modification? Here? It's fixed that, uh And as you can see, we get to our third position and we send to continue commend, but all keeps going normally. Now let's have a look in a while. Come in here it acts differently. So I declared the area I put my X equals zero. I start going through it if I hit position three I send to continue. Commend. If you commend this out here, you will end up with an infinite loop because when the continue will be sent, X will still equal treat will not move it to the next position. So I put that dare the incrimination of X in order for it to be able to continue If you do not, If you commend out the incrimination of eggs and you evaluate it in organ mode, I will show you here. Let's do it. So let's come in comment this out. So if I attempt to execute it now, the execution will not complete. And it seems less. If iMac is crashed, just press control g to quit the evaluation midterm or anywhere eso that shows you the difference and continuing between the for loop and a while, or until so that finishes our classes or section on loops. In the next video, we're going to start looking at how you pass arguments to, uh, your script 16. Command Lines arguments: Good morning. Uh, now let's have a look at how we passed arguments to your script. Ah, passing arguments to your script, where he's very similar to a passing arguments to a function he can be accessed starting from Dollar Juan, Dollar two and so on. So let's first have a look and a literal example here, going through a list of, ah, command line argument with a four loop. So I opened up with she bag and then four I and this is assembled to use to act, test all the arguments in a for loop do echo dollar. I done so a very simple script and an organ mode here. This is the argument leads that I pass and I'm going to pass two more arguments I'm going to evaluate. And as you can see, my are Guan and all the arguments that I passed on the command line. So that's a simple way to past 30 command line argument. Would A for loop Let's have a look at doing it with a wild eso. I initiate extra zero. I assign all d command line argument to a variable area, call our eggs, and I do my usual while while X is below the number off element and the area argh echoed M and increment DX. So if I print out the results and you can see that my command line option or over here although how are you? And they are printed each on a single line in the next session, or going to see how you can implement Lennox style argument into your script, I mean, like, short and long option Combine option that, say you do ls Dash l eight eso We're going to look at that at the next session here. 17. Linux style args Part 1 (Space separated): So how do we implement Lennox style arguments into your own script? They are three common ways of doing so. Let's first look at the 1st 1 to space Separated option. You would call your script with the fall away Met method. Uh, you would call the name of the script, and then you could pass in a short option. Lets a dash A or Dashti or Dash V. If the option takes a value, you would put a space in the value. Or you could use the same method except with long option names than space and value. If it requires one. This method does not end all handle. Combine option lets a dash L eight to provide two options. Let's have a look at the code here. Eso here, I declare it three variable. Now, this technique uses a key value technique. It handle short and long option the way this program So I would create a four loop like this year s O. That means that while the number of arguments in the argument supplied list is above zero, keep going. We assigned number one to the key. Did we check the Dickey in case it against all of these option Here we provide a short option than the pie assemble that means or in the case statement. So I could also do. And that's a provide a Not so that would be like this that would render that option available and good toward a command line. Then I assigned the value option to the number two. So when you do a loop like this, it will always be a key value way of seeing it. What? Well, where the first part is the option. The short option long option that goes into key, which is number one and number two becomes the value of the option itself. Once we have used those key and value, we have to shift the number of arguments that are still in or less to use. Basically, this one here so I do a shift to that means is going to shift my argument list by to removing to 1st 1 on the list falls off in the next to come into place. So same thing for dash file. Now, Dash D is not a non option that takes an argument. You just supply it or you don't. And so we only shift by one. And this here is for any other option that we don't know about recording. We don't know the option, Uh, and then we provide the shift command. After once this all done, we simply print out the value of our three options we set up. So let's see what the results of this year. So once again, I passed my command line argument through this part here, everything before the redirection of standard, ever. So if I do it like this, see that? The passing argument and it got all my options. Right now let's go for the fund and provide a unknown option. But this is telling me that it doesn't know the option. Dash eat now. If I was to do an error and provide an option for that, I think would contain a value but is not in the case. It sees it simply as an option, and there's an error because it doesn't know what to do with it. Now. If I was to attempt a about a combined option, you see it does not recognize those two option at this point. So this is how you would implement a space separated Lennox tell argument list in the next session, we're going to look at a different way a equal separated method. 18. Linux style args Part 2 (= separated): So now let's look at a different method. We are going to look at the equal separated. Ah, do you? Such is fairly similar to the space one, except that instead of a space we put unequal sign, this method does not end all combine option either. So let's have a look at the code here it is slightly different. The loop is different in this case for I and this means all the argument passed through the command line and then we do a case on the I. And if you look at the options we have are short option are equal sign and then a star symbol. So basically, I will contain your whole dash option equals, I end. The value will be included inside that I variable and down first line here we actually extract what comes after the equal sign and assign it to our value. So we only need to shift by one same thing for the dash file and same thing for if we don't know the options. So let's quickly run the script and see the results done passing so as you, it works exactly like we were expecting. It works exactly like the space separated except we put unequal sign. But the structure of the code is slightly different. In the next session, we'll look at using get ups bash built in that this time does take a combined option. 19. Linux style args Part 3.1 (getopts): Now let's look at our third option to implement Lennox style argument with bash Bail temp. Get officer commend first get ups. Onley handled short option. There is no long option into it it But it also handles, change or combine option like dash V f or L s Dash L. A. There's a different reference link here. Just crawled down to the get ups A note. If you run, man and then you write get opt no s It is not the same. So the usages get ups up String name and arguments in the brackets here. So let's first have a look into more detail about usage. So get up is a bash Bilton up string contained the option characters toe look, for example. Or if G means we're looking for the short options that's owed ask FSG or any combination. So let's have a look at the example code here. So using a while loop while get ups in, uh, in here you put the options that you are looking for and this is the variable that is going to be contained. So it's basically going through. The first option is going to put the option name inside O P. T. And execute an echo it. So let's see the results here So you can see that I put my command line arguments here, and it lives them in that same order. If I was to change them like this, it will change the results. And if I was to mid one, it does not show it. And what happens if I put another one that I'm not looking for? It complains about an illegal option. Now. If a character is followed by a column, the option is expected to have an argument. In such case, Get Ops plays the argument in the variable, and it is case sensitive. O P. T A R G Kate. No, let's have a look at the code quickly here. So I declare some variable to play with. Now, in this example here, the option f is expected to have an argument. So we are looking for the option O g. Stand alone and F is expected to have an argument. This is our key structure here, where we assign value to 20 p. T a r g. When it is a notice, and then we print out our option So let's have a look here if I does our to command line argument that I'm sending to the code block that's removed just so we can see the new one air you go and you can see our options right here. Now let's change this and let's put a space in for the dash F option. It does not make a difference. It still places it, and you notice there is no space in between here now. If I was to amid the argument here, it throws us an error that the option requires an argument. I will replace the argument where it goes here. We run it, and there's our options. Every time it is invoked, get UPS plays the next option into a variable and the index of the next argument to be processed in o p. T i N D. That's a variable once again, case sensitive. While this variable is B will be set to one every time the Shell script is involved, it does not reset itself automatically after. If you are to call get ups multiple time, that variable has to be reset manually. So let's go have a look at the example here. So I declare my variable to play with and I echo what the OPD I Andy variable? It's set. When the script starts, I go through the options and I echo that variable every time we go through the loop. So you will see it go up Now we are past that while loop and I give you that same variable here. Now we are attempting to redo the same loop without resetting the variable toe one and then we'll see what happens. So let's run the results here. My options are the same. They are old, valid, so you can see we start at one. Then we go to to Then we go to three and then we go to five because the last one has an option. Now we're attempt to redo the same loop without resetting it. And you can see we reach the last echo without doing anything down here of the end while Lupus finish because we did not reset it. So just remember, it's always a good habit. Once you are done using upto get ups, always reset that variable back to one 20. Linux style args Part 3.2 (getopts error): keep no, let's look at get ups and errors by default, error message or printed with an invalid option or messing option argument is encountered. So the following script does not supply an argument for option mine for option F. As you can see back here, the code is very similar to what we've seen before We display that is expected to have, ah, argument, and it doesn't have. So let's run descript here and you can see that we have, ah, error complaining about the required argument missing if the first character and up string as a column silence mode is used. So here we have the same code, except I started with a call in here and the options are the same. I missing the arguments for option F. So if I run this script here, it does not complain about it. If the variable o p. T err except zero, no message will be printed even if you do not use silent vote. So I'm going about the same mistake again. I don't have silent mode, but I said it. Uh oh, Petey, err to zero. So that's run that script here. And even though I'm missing the option and I'm not Ah, in silent mode, it still does not printed nearer when an invalid option isse found the value would have a question Mark is placed in name upped arguments is unset and a diagnostic messages printed by get ups. The code block will supply an invalid option Dash X, which we can see here. Now the code is back to the same as what we had it, except in a case statement. If my O p. T. Is equal to a question mind, that means we encountered a invalid option. So let's run the script here and now we see the error message printed by get ups and the message that I printed in the case statement. So and if get ops is in silent mode, up target is set to the option option character found. Eso will give a quick example here. Look at the code quickly, so it's the same code. Still, I am in silent mode when I encountered the error. So the values a question mark of OPD I will print out O p t a r g, and you will see what we mean by this. So you see, I have an invalid option. Eggs. It is the its value. It stored it up hard. If a required argument is missing and get ops is not silent, a question mark its place in name and opt argues onset and diagnostic messages printed. So in desk case here, OPD err is set to zero. We are not in silent mode. I will encounter that question. Mark and I will print out the same variable O P t and o P. D a R g. So let's see the results of that one missing argument detected. Get aswell display an error message So you see that there is no value indoor section here. Last point about get ops an error if a required argument is missing and get ups is silent. A colonise placed name up Argus set to the option found and dying Diagnostic message is not printed. So let's look at this so even right enough, I would set this toe. One would only suppress the error messages, but we are in silent mode, so I look or not the question mark, but a column and I print out the same error messages as before so you can see missing argument detected get obsolete. Not this play an error message, and we know that is the dash F option it requires on argument. So in the next class session, we are going to look at making menus with Cilic built in to allow you to build what's called T u wy text user interface. 21. Create menus with SELECT: welcome in this session here we are going to learn how to make menus with Selig built in command. Uh, no. That descript in this section here produce interactive scripts, so it needs to be run a terminal. You need to export to code. Uh, the select built and makes it easy to display and directive menu to the user in a command line interface destructor. The structure is select word in less and then do what you need to do and then done. So it's kind of like a while. Loop list is expanded and a list of items has generated from it. The expansion is printed to STD error. The file descriptor number two due to the interactive nature of descriptive must be exported. So let's have a look at the code here. So the following script will give you a menu of all the directories in your home directory . And after making a selection, it will this all the files in that directory. So what's happening is first of all, we do a loop, then we select the name here is going to be what she was a variable. This here is our list. So this first section will put all the directories in your home directory into that list. And then we also add the extra award Quit. We start our do loop. Now. If the variable the i r is equal that quit, we exit. Otherwise we'll is the content. So let's export disc owed go over to a console and this is a simple select. So this is all the content of my home directory. Older directories. So fight select three. It lasts the content of my document directory. And if I had 14 it quits. Descript sub menus nested Select statement creates sub menus. So let's look at this here. So we start the same thing, but first here we pushed the or home directory. Okay, Push D is a better alternative to change directory in the script. Okay, Bash keeps a drug stacks of older directories. So what we are doing is that we are pushing your home directory on top of that stack. The reason why redirect a slash deaths national is because every time you call Posey or Pop D, it will print out the directory stack to STDs. So we put our own directory to the top of the stack and then Select Star. None just directories all the files and we had quit. Same thing here. If we find quit, we exit. If it is a directory, we pushed a directory. On top of that stack we selected to sub d i r star and back. Okay, If sub hair is back, we break the loop. So we fall back into our parent loop here. If it is a file, we print a content. Be careful which, while you select for examples and file or binary file, can print out a long, long time. If it is a directory, Well, is the content of that directory? This year should not happen. So until we hit back, it would break. And then it would pop the directory that we pushed right here. So if it's not a directory, if it is a file, we simply can't the content of it. And at the end of it re pop our own directory re pushed at the top. So let's export. And that would be Ah, let's see, that's last year. Selects sub. Okay, so let's run the Select seven manuscript. So this is my whole content inside of my home directory. So if I sell like 16 test that s H fate file, it prints out the content. If I push under with nothing, its simply reprints the same Select Luke. So if I was to go into three my documents, I've entered that directory and it prints out its content. So if I check test, it s h there. It's a different file. And if I look into another directory number four, it prints me out the content. But I am still in the same loop. So I fresh seven for back and I am back in my home directory, 20 to quit and the script is done. So that's it for the basics and beginner class for introduction to scripting on Bash in the next session, I would like to talk about a project that I would like you to try. 22. The project: Now let's talk about a project to practice pretty much everything you've learned. What I propose you do is I propose that you use bash scripting to create a very simple ah file manager. It doesn't have to have many features. You can choose the future as you want. And as we move forwards toward Mawr advance topic, we're going to elaborate on that file manager script. So I have included a two version of that that file manager. They dont both have the same functionality either. Eso I will describe the way it is entered in order mode here, so it makes sense for you. Uh, first section of code that we see here is called a script export. If you want to export that version of the farm manager, you go on that code and you press the export function Control you control C control the deep, so this will export the whole coat. Let's look inside of it. There is actually no code in there. The only thing is that this one includes reference to the other code section. The reason why it has done like this. It's because this is quite an interactive script orig mode is not good. It's good at evaluating. But it's where more complex when you want to do interactive scripting. So to avoid errors each of the next section or each one of the function. Okay, so you can look at them each and very, very separate an isolated ways. They cannot be evaluated. They cannot be exported. If you want to export your export, this one here, which will refer to each of the other coat, I won't go through exactly how it's done, which you hear. If you have question you want to elaborate on that, join me on my Facebook group and post on that. OK, this is another version of descript. It uses Mawr to select eso built in function that we talked in one of the previous versions . It also has a different feature where it is allowed to rename a file. So I will let you go through those codes here, give you some ideas and come up with a script to make A simple file manager doesn't need to have a lot of features. Um, if you require help, our clarification join me on my Facebook group post on there. If there's question about my functions. I will happily described him to you. But I would like to let you a exercise your own judgment for a little bit and post your project on my scale. Cerda Project section Thank you for following this class and, uh, hope you will join me in any future classes for Lennox.