Linux For Programmers #11 - Shell Scripts

Creating an If Statement in Linux with Control and Read Commands

=================================================================

In this tutorial, we will learn how to create if statements using control commands in Linux. The syntax for creating an if statement is very straightforward.

**Using If Statements**

---------------------

To use an if statement, you need to start by typing "if" followed by the condition that determines whether the code inside the if block should be executed. Then, you need to put a semicolon after the condition and then type "then". This will indicate where the code that should be executed starts.

For example, let's say we want to check if "tim" is equal to "tim". If this is true, then we can print out "tim is great!". Here's how we can do it:

```bash

control tim && echo tim is great!

```

As you can see, the control command has been used here. This means that the code inside the if statement will only be executed if the condition before it is true. In this case, since "tim" is indeed equal to "tim", the code prints out "tim is great!". However, let's test this further by adding a second call with "bill":

```bash

control tim && echo tim is great!

control bill && echo bill is great!

```

Notice that we get "tim is great!" but "bill is not great" because the if statement only ran once.

**Using Else Statements**

----------------------

To add an else statement, you need to type "else" after the then. This means that if the condition before it is false, then the code inside the else block will be executed.

For example, let's say we want to check if "tim" is not equal to "tim". If this is true, then we can print out "tim is not great!". Here's how we can do it:

```bash

control tim && echo tim is great!

else echo tim is not great!

```

As you can see, the else statement was added. Now, when we call control with "bill", we get both messages because the if statement ran once and the else ran.

**Using Elif Statements**

----------------------

You can also have multiple conditions inside an if statement by using elif (short for "else if"). This means that you can add more conditions after the first one. Here's how it works:

```bash

control tim && echo tim is great!

elif [ $2 == "joe" ]; then

echo joe is great!

```

As you can see, we added a new condition that checks if "$2" (which represents the second parameter) equals to "joe". If this is true, then the code prints out "joe is great!".

**Getting Console Input**

------------------------

To get console input from the user, you can use the read command. The read command takes two parameters: the variable name where the input will be stored and the prompt that appears on the screen when the user types in their response.

For example, let's say we want to get the user's name:

```bash

read -p "Name: " name

echo $name

```

As you can see, we added a prompt with "-p" which means prompt. The variable name is stored in "$name". When we run this command, it will print out whatever the user types in.

To store the input from the previous example to the variable "text", we need to change our script slightly:

```bash

read -p "Name: " text

echo $text

```

This way, we can access the stored value of the user's name later on by using the dollar sign.

"WEBVTTKind: captionsLanguage: enhello everybody and welcome to another video in this linux or programmers tutorial series in this video we're going to be covering shell scripts now shell scripts are a way to actually execute shell commands within a script so you can think of it just like any other script that you might write and say a programming language like python except instead of having python syntax you're having shell syntax so you can still implement things like loops if statements uh conditions you can have statements that execute and expressions that evaluated and i'm going to be showing you most of that in this video regardless shell scripts are good to know and as a programmer you should definitely have an idea of how they work and at minimum be able to read them so with that said let's dive in after a quick word from our sponsor which is lenote lenode is the best company to use to host your website app or service in the cloud if it runs on linux it runs on lenode and leno just makes it really easy for you to get your server up and running as fast as possible so with that said check out lenode from the link in the description and make sure to claim your 100 in free credit when signing up with a new lenode account all right so let's dive in here the first thing i want to show you how to do is just make a shell script so when i say shell script all i'm talking about is a file that has shell script syntax inside of it that allows you to actually execute that file and then have these commands run so let's create a really basic one i'm going to use nano as my editor here but feel free to use vim emax whatever you would prefer you just have to make sure you type the same thing that i am so first of all we need to make a shell script file now all shell files are all shell scripts whatever you want to call them end in dot sh so after my nano command i'll just type test.sh and this is going to be our first script uh let's go ahead and press enter all right so now we're in nano and the first thing that we need to do in our shell scripts is we need to add what's actually called a shebang now i think this is a hilarious name but this is actually the name of it and what this is is a pound sign an exclamation point and then the name of the shell that you want to run this file in so you don't really have to understand this but we're just going to do slash bin slash bash and what we're saying is that we want to use bash to run this file so whenever you make a shell script you're usually supposed to at the very top tell the shell script by adding this little comment here what shell you want to run this in now there's multiple shells bash is just the most common one and the one that we've been using and well that's the one that we want to run this script in so again that's called a shebang you always add that at the very top of your file and 99.9 percent of time it's going to be exactly what i have right here now the next thing i'll show you just how you actually write a comment in this shell script so a comment is simply a pound sign like i just did above and then whatever you want anything that is after a pound sign is not going to be executed in your script so think of this like any other comment that you would see in any programming language it's just this is how you do a comment now some people may be confused that our shebang was actually a comment but since we have this exclamation point it kind of differentiates it so that's kind of the main difference all right so now that we have that let's write a really basic script all i want to do here is just echo some things out to the screen so i'm going to say echo and we're going to go with our classic example of hello world exclamation point then i'm going to type echo and just hi now anything that you can write in your regular command line so in the linux terminal in in bash you can write inside of here so i can type ls hyphen l right or ls hyphen a or whatever i can type all these commands here and they will just execute as a script so when i run this file all the commands that i type will execute so let's just start out really basic with some echoes so we're going to have our two echoes there i'm going to exit and now i will show you how to run the shell script so to run the shell script you're going to type dot slash and then the name of the script which in our case is going to be test dot sh now notice that when i try to do this we get permission denied why are we getting permission denied we're the root user we should have permission to do everything well the reason we're getting permission denied is because if we have a look at this file i believe it's ls hyphen l and then we say test dot sh we can see that we do not have execute privileges on this file so what we are trying to do is execute this file so what we need to do is add the permission to execute this file so what we'll do is we'll say chmod plus x and then we will say the file name which is test.sh so now that i do this let's have a look at the permissions and we can see that everybody can now execute this file if we just wanted to make it so that we could execute this file well we know how to do that i showed that in the chmod and permissions video but now notice that test.sh is showing up in green which means that we can execute it so now we can execute it with dot slash test.sh and when we do that notice we get two print lines out here we get hello world and hi which is exactly what we wrote in the shell script so that is the basics of shell scripting but now let's show some more things that we can do inside of here and again this is not going to be an exhaustive tutorial i'm just giving you an idea of how to run a shell script what a shell script is and basic stuff that you can do inside of it but you always need to make sure that after you write your shell script you give yourself permission to actually execute the script by adding the the execute permission to your user or to all users that have access to the file all right so we have our two echoes now what else should we do well let me show you how we actually implement a function inside of a shell script so i'm going to assume that you're familiar with functions uh if you're not they're pretty straightforward you'll probably understand how they work but i'm going to say actually why am i calling this today i don't know let's call this uh print okay we're gonna put two parentheses and then open some squiggly brackets and this is how you make a function in a shell script so you put the name of the function two uh parentheses or brackets whatever you wanna call it and then open up these curly braces here and then inside of this function usually you tab in or one two three four characters uh inwards you don't have to have this indented but usually that's convention then you can write whatever you want to happen inside of this function so i could say echo and then let's just say called function exclamation point and then what i could do is i could call this function so to call this function is how you would assume we just write the function signature like that and while we can use it many times so now we're calling this function four times and yeah let's just give this a shot so now let's escape and let's run this file and we see we get a syntax error and that is totally my bad i just made a small mistake here we actually don't have the parentheses when we call this function sorry this is my bad i don't know why i added these but we can remove these and if we just called a function like this this should work now so now let me escape let's run this and now we can see that we called the function so when you call the function all you have to do is just write the name of the function you don't have to actually put the parentheses afterwards now let me show you how we can pass arguments to our functions or how we can you know handle parameters and stuff so remember that when we were talking about environment variables the way we accessed them when we were say printing them out was we used the dollar sign now inside of the shell script this is the exact same thing whenever we're accessing variables even ones that we've defined inside of this script and i'll show you how to do that in a second we use the dollar sign to access them so let's say i wanted to pass something to my function here what i would do is i would simply write after the print function call whatever value i wanted to pass so i could say print and then tim is great like that now i could pass this as a string if i wanted to pass this as one argument but if i wanted to pass multiple arguments i want to pass tim then is then great i would do it like this so every time you want to pass multiple things you separate them by spaces if you just want to pass one thing and say it's a string for example then you would have to put this inside of quotation marks now i'm kind of assuming you guys have some understanding of programming so that's why i'm skipping over a lot of stuff here but let me show you now how we would actually print this out so we're passing some value to our function now how do we actually get that value from inside of our function now some of you would assume that we do something like this right that's actually not what you do if you want to get the value that is passed to a function you use dollar sign one dollar sign two and all the way up until the number of values that you pass to this function so in this case we're passing one value to this function so the first parameter is going to be identified by dollar sign one now if we wanted to access the second parameter or the second argument that would be dollar sign two right so that's kind of the idea here so let me just show you this i'm going to say echo and then called function and then inside of this string i'm going to put a dollar sign we'll go like that and then we will put number one so now what this should do is print out whatever we pass to it as argument or parameter one so let's run this now and we see that we get called function and then tim is great but for all of the other ones it didn't pass anything or nothing showed up because there was no dollar sign one so that is how we pass parameters or arguments or whatever you want to call it to the function we use dollar sign one and then just to show you an example here let's say we were to print one two now if i say dollar sign one and then dollar sign two i now will be able to access both of those values so let's run this and we see that we get called function 1 2 we passed both values to our to our function all right so let's go back inside of here now that's the basics of functions and how you pass values through now let's describe how you make a variable so making a variable is really easy all you do is you type the name of your variable so let's say x equals sign without a space and then what you want it to be equal to so in this case we can say you know what let's say x equals 6. that's all you do when you want to make a variable now typically when you're making these variables or sorry not typically when you're making these variables you cannot have exclamation points in your variable names you cannot have spaces in your variable names and you usually do not want to start your variable names with numbers now i'm actually not sure if you can or cannot start your variable names with numbers but the convention is just to use text you can end the variable name and number if you wanted to and if you needed to use a space you would use an underscore instead so say i wanted my variable tim is great then i would go tim underscore is underscore great just like you would in most programming languages so let's say x equals six and now after we do all our calls to the print function what we can do is we can say echo and then dollar sign and then x now this is going to access the x variable and print that out now i might have made a small mistake here but let's just run this and see because if i made a mistake well that'll be a good learning opportunity but let's get out let's run this and notice that now it does indeed print six now the reason i thought i made a mistake was because i thought you might have to put that dollar sign inside of a string but it turns out that you do not you can just access the variable directly and it will print it out so let's go back in there so now what i'm going to show you is how to implement control flow so if else lf all that and then i'm going to talk about something called exit i'm actually going to start with exit because this is pretty important every time you have a linux process or a linux script or whatever it may be when it finishes running it has an exit code now by default that exit code is just going to be 0 which means you know this was successful but it is good practice in your shell scripts to implement your own exit codes just to make sure it's very clear that hey this script finished successfully or no this script failed now there's a bunch more exit codes as well i'm not going to really go through all of them but all of this is to say that when you end your script and all was good you exit with the code zero now whenever your shell script hits this line hits exit zero it immediately stops the script stops processing everything and then returns this code to whatever called it now is it's a bit more advanced than that but that's kind of the basics and if you exit with code 0 that means that everything was successful script went well if you exit with code 1 that meant that there's a failure in the script so you're telling whatever called this hey this script failed so just keep that in mind exit code 0 success exit code one failure so say you have some exception that gets raised in your program or you just want to all of a sudden exit out of the program and tell them hey you know this failed you would just write exit 0. now in fact i can kind of prove this to you even we can do exit 1 as well but inside of this print statement if i type exit and then let's just go with 0 which means success after i call this print statement the first time the script is going to end it's going to stop running so we won't see the output afterwards all right so let's run this script and notice that we call this function one time and then all of a sudden it exits so now let's just see what happens when we go with exit one instead of exit zero just to show you so we'll change the exit code and then rerun this and you know same thing happens we don't see that the exit code was one or zero but if you were running this from another script you would be able to check what that exit code is and there's some other more advanced things but anyways when you see exit or when you write exit it will just stop the script immediately and that's good to know so we will continue in one second but i need to quickly thank the other sponsor of this video which is algo expert algo expert is the best platform to use when preparing for your software engineering coding interviews and they feature a data structures crash course over 120 coding interview questions mock interviews and behavioral interview prep and a ton of other really valuable things check out algo expert from the link in the description and use the code tech with tim for a discount on the platform alright so i'm back something went wrong with my screen recording software so i had to restart but notice that i've emptied my bash script now what i'm going to show you is if l if and else statements so these are pretty straightforward and i just want to make it clear that i'm not going into a ton of depth here i'm just showing you kind of some working knowledge this is not discussing how everything works on a low level again i i could spend a whole tutorial series talking about bash so this is just a high level overview anyways let's write a function here i'm going to show you how we can implement if and else statement so i'm going to say control and then i will open my parentheses and inside of here i'm going to write my first if statement so i'm going to say if and then i'm just going to first of all end this if statement with fi so whenever you write an if statement you need to end it with fi now fi will go at the very end of your entire conditional block or entire control statement block so in this case we just have an if statement but we also could implement and l if so let's go here we could say alif like that and then we could say else as well so just keep that in mind you can have if else and l if i will show all of them in one second but you do need to end the entire conditional block with f i alright so we have if now if we want to write an expression or a condition to be evaluated here what we do is we use a double set of square brackets like this now i'm not going to explain why we're using these square brackets but what this does is evaluate an expression now there is also another way where you use single brackets but double brackets are kind of the standard right now and for our purpose they just make more sense so you can look that up on your own i don't want to talk about it anymore but we'll use the double set of brackets now inside of the double set of brackets what we can write is an expression now there's a ton of different expressions in bash and you can do things like check if file exists you can compare strings for equality you can perform arithmetic operations and check if two numbers equal each other it's a lot of stuff that you can do but i will show you the most basic comparison which is just comparing two strings so what i'm going to do is say number one which is going to be our first parameter is equal to notice that i have a space here and that i have a space between my first bracket and then whatever string i want to check if this is equal to so in this case i'll say tim so what i'm doing is i'm checking if the first parameter past this function is equal to tim then the syntax here is a semicolon to end your condition or end your expression and then you type then and then underneath here usually indented but doesn't matter you type what you want to happen if this is the case so i'm going to say echo and i will just say tim is great exclamation point okay so that is our first if statement let's show how this works i'm going to call control and i'm going to pass tim and then i'm going to call control and i'm going to pass bill all right so i saved the file i'm going to exit and i'm going to run this and then notice we get tim is great but it only happened once because of course the second call to control that we did was false right the if statement didn't run okay so let's clear that let's go back in and now let me show you how we do else so this is pretty intuitive but to add an else you quite literally just type else and then underneath the else you type what you want to happen if the condition is not true so i'll say echo tim is not great exclamation point all right so let's run this now and notice that we get tim is great then tim is not great so the if ran and then the else ran okay so now let's do this again i will show you the l if again very straightforward and just like in other programming languages you can have as many lifts as you want so you can say elif then you write your condition put your semicolon and then put the then so now let's actually check a second parameter so let's say number two is equal to and let's go with joe and now let's call control so let's say control and we'll go with bill and then joe so now we should hit our l if in this last control call all right so let's escape and let's run this and oh we got an issue here syntax error unexpected token else let's go back in here what was incorrect ah well i forgot to add something to do in our laf so let me just add something the reason we were getting an issue is because we didn't have anything after the then and well we did we had else but that's just the incorrect format we need to have something to do in the alif case right so now what i'm going to do is say echo and then we'll just say geo all right so now let's run this and just yeah all is good we get tim is great tim is not great and then joe okay so that is if l if and else again you could have many more elifs as you want just make sure that you start with an if and that you end with f i okay so that was pretty much all i want to show you one last thing is how you get console input now this is actually pretty straightforward the command is very intuitive it's actually called read so what i'm going to do is show you how you can get input from the user and then how you can print out that input so let's say you want to get the user's name or something what you can do is you can type read now read pretty much means like let the user start typing and then you can do hyphen p now hyphen p stands for prompt so this means if you don't want to just have an empty line that the user starts typing on instead you want to put something on that line so say like name colon and then the user gets to start typing you would do hyphen p you would do your prompt so like name colon like that and then lastly you would put the variable name that you want to store the uh the value that's typed in in so i would say the following i would say read hyphen p the prompt and then text now what this will do is store whatever i type in the variable text so what i could do now is say echo and then dollar sign text and this will simply print out whatever the user typed in on this read line now i understand this is maybe going a bit fast but let's just run this and see how this works so when i run this notice it says name i can type let's type hello and then it prints out hello because well that's what we typed in so really straightforward you can add the prompt you don't have to add the prompt if you don't want to add the prompt then you just remove that hyphen p and the prompt you put the variable that you want to store this in notice that i didn't have to define this anywhere else i just typed the name of the variable then you can access the variable later on using the dollar sign like we've done so anyways i hope this was helpful if it was make sure you leave a like and subscribe and i will see you in another linux for programmers tutorial video\n"