Bash Scripting - Variables, Arrays, If-Then-Else

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
have you been wanting to do some simple bash scripting but you're not really sure how to get started you're not really sure what you're doing as far as bash and bash scripting well today I'm gonna cover some of the basics things like variables arrays if-then-else and some other things so follow along and I promise you at the end of this video if you follow me step-by-step you should be able to create your very first bash scripts let's get started before we get started there are a couple of tools that you will need in order to do this bash scripting first you're gonna need a text editor of course right we're about to do some programming so you need a plain text editor today I'm gonna be using Emacs if you know vim them's a great text editor Nano would be fine at the command-line if you wanted a graphical text editor G edit is great Jeanne's good vs code sublime atom pick whatever plain text editor you want to use whatever you know and feel comfortable with I I'm going to assume you know how to use your text editor of choice I'm not gonna cover how to use whatever text editor so make sure it's a text editor that you're comfortable with also you're gonna need a terminal emulator of some kind so pull up a terminal yes you're gonna have to do a few things at the terminal I assume that you have at least a very very basic knowledge of the shield you don't have to be a command-line wizard but you should be able to bring up a terminal and run a few basic commands so let's get started so the first thing I will do is I'm gonna pull up both my text editor which is Emacs here on the left hand side of the screen and my terminal emulator here on the right-hand side of the screen let's go ahead and create a empty document so we can go ahead and write a script so I'm in my terminal I'm in the home directory here in my terminal first thing we need to do let's create that empty document the easy way to create an empty document at the command-line is touch and then space name up document i'll call this new shell script new dot sh alright and let's go ahead and open that in our favorite text editor if you're already in the terminal you could open up in a text-based terminal-based text editor like nano or VI or VM or Emacs if you do Emacs in the terminal I do the graphical version of Emacs here so I'm gonna open that file new dot Sh alright now let's begin writing first of all let me consume in here I'm gonna zoom in a little bit so you guys can see what I'm doing here in Emacs now the very first thing you should do with your new shelf script is app on the very first line write shebang which is the shebang is the hash symbol followed by the exclamation symbol and then the path to where Bash lives on your system which should be slash bin slash bash now I say it should be that it could be somewhere else so if I go back to the terminal let's make sure that Bash is actually in that location I could do it where is space bash and I'm running arco Linux which is an arch based Linux distribution the binary for bash actually is not in slash bin slash bash it is in slash user slash bin slash bash now there's probably a link linking slash user slash bin slash bash to bin bash so this would be fine for your shell script it's not like it would harm anything but if I really wanted to just to be on the safe side I could do the shebang followed by user bin - there's one other way to do this a very common way is to do slash user slash bin slash env for environment space bash and that no matter where bash is on your system that should have you covered so that should always be the first line of your bash script the next thing I often do at the beginning of my scripts is to leave a comment letting other folks know exactly what this script is to leave a comment a comment is basically a line that's not really code it's not going to be executed when you execute the script it's not really programming code at all it's just leaving yourself a note and leaving a note for others that may view this script at a later date so you do that with the power symbol and then type whatever you want to write whatever you give me this fits a note say this is a test script and that's it that's that is your commented line again this is not actually code it's not gonna be executed when you run the script this is just a note for you you can leave notes all over your scripts I often leave a lot of notes in my scripts especially if it's something confusing like if I go back and I'm reading the code and I'm not exactly sure what that code does I'll leave a note hey this code does this and this line does this this does that any of you guys that have pulled down some of my scripts for my get lab page know that in my configs and my simple bash scripts I often you know do something fancy you know it was with the comments like it's not unusual for me to leave a comment that looks something like this well ASCII art DT with my name location of my YouTube channel and of course location to my git lab repository now Lex let's actually do something with the script because again all we've done so far is listed the path to where the bash binary is on the system and we left some comments but that's not really code right there there's nothing that's going to be executed when we've run this script right now so the first thing we need to do is actually have the script do something have it execute a command now what kind of commands can you have your bash script executes well pretty much any command you could do in the shell so this is the the shell here which is bash as well so pick a command how about LS you know you could have an LS command well while we have a script that runs LS I know that seems kind of pointless but again the sky's the limit on what you can do but let's go ahead and I'm gonna save that and let's see if we can actually execute that how you execute your shell scripts at the command line as you need to do period slash and then the path to that script which is new dot shell it says permission denied okay so when we created this document this new SH document we did not make it executable so how do you do that you need to chmod and then plus X for executable and then the name of the document new dot sh run that and now when you go back and execute that script which is period slash new sh it will actually run and what did it do well it ran the LS command right here in the terminal so that is actually your script again period / new if I hit enter it runs the LS command if you wanted to get kind of crazy I mean have it execute this command Firefox let me save it then go back to the shell here clear the screen rerun the script what does the script do it launches Firefox now it's kind of pointless to have a script that executes a command like LS or Firefox because why wouldn't you just type LS at the command line or you know launch Firefox with your run launcher or through your menu system or even at the command line but where bash scripting gets interesting is when you need to do complicated stuff or example have you ever wanted to run a CH top although like a command line program like a CH top for example and you tried to run it from a menu or from your run launcher and you type H top hit enter and it doesn't execute well why doesn't namely X acute it doesn't execute because H top has to run inside a terminal H top requires you to first launch another program a terminal and then for an H top from inside that for example if I run D menu right now and I type the command H top which H top is installed on my system I fight you dinner nothing happens no first I need to actually open a terminal and then run H top this is where doing something like a bash script is interesting because obviously you can do multiple commands and a bash script you can tell it hey open my terminal my terminal by the way is st but you could use whatever terminal you want to use genome terminal or X term whatever terminals on your system write the command to launch it and then do a semicolon and then each table now let's save that control yes for save make sure there we go of course that's a Emacs command we're not discussing Emacs today save that shell script and whatever however your text editor saves things and then let's rerun new dot SH and what does it do it launches a terminal well it launches the terminal but it didn't run each time what happened here well let me close this terminal that it launched and what it looks like terminal it launches it runs H top in the very first terminal that I executed the script end got a weird right kind of weird behavior now of course we could clean that up and actually make that work the way we expect so I can run this command st space - e which tells st basically derp open itself in a new environment and then I need to actually tell st in quotes to run htough now let me save that and I bet this works as expected now when I run this script it's going to open up a new terminal and in that new terminal and run htough there we go course we could get even more creative here you know I could have this script launch st and then h top inside st and then let's hit enter and on a new line they also launch Firefox and on the next line why don't we tell it sleep for three seconds after you launch Firefox and then after you wait three seconds why don't you launch Jeannie which is a graphical text editor I haven't installed in the system as well you know what let me save this document let's execute the script and see if that actually works there's H top now it didn't go ahead and launch Firefox but I bet if I close s T and H top it will launch for the same thing as before by close Firefox it's gonna wait three seconds and then it's gonna launch Jeannie right perfect timing on there let me clear the screen on that so how we need to do this is we need to tell it instead of waiting for one to execute and then close and then open the next one now we should do that is let's add and for sign that an ember sign at the end of each line so you know open up a CH top and side st and Firefox and you know and then sleep three seconds and then run Jeannie then let's save that and let's see if this is the expected behavior yes they say it launches all three of course it did it wait the three seconds Jeany seemed like it popped up pretty quick let's execute that again just make sure so H stop and Firefox should load immediately Jeannie should take three seconds Jeannie is coming up before Firefox H stop Jeana so it's not quite I think the problem is that last ampere sign behind the sleep because it's not waiting for sleep to finish you know it's just going ahead and launching Jeannie if I remove that last ever sign so sometimes you have to play with these things you know I actually did not expect that to happen that was a genuine shock when Jeannie launched so fast let's see if this works as expected now it's waiting three seconds and boom there's Jeannie so that is why I needed to remove that ampere sign so one of the basic things you will want to do in your scripting is declare variables you know set up variables for example say I had a very long script where I did a lot with terminal programs and and like there were a hundred lines in this maybe it's a config file for a tiling window manager where I executed s T which is my terminal well instead of having so many places where s T is in that script maybe I substitute it for this variable I'm gonna say about my term equals and then s T now if I wanted to I could do something like dollar symbol my term and then - e H top etc etc so if I go ahead and save that and let's go ahead and execute it and again the script runs just fine so that is how you do variables again you just set up the main thing you want to do with variables main point you want to make sure you don't add a space but before or after the equal sign so do whatever the variable name equals with no space and then what you want that variable to actually equal to in this case it was a command I want it to equal to St now why would I do something like that well imagine like my X monad config and all my key bindings that involve the terminal in some way I have a hundred lines where s T appears well what if one day I decide I don't want to use s T as my terminal emulator maybe I want to use X term or you are xvt there would be a hundred lines in my config file that I have to go in and edit and replace s T with X term or whatever well if I set up a variable and then in the script that those hundred lines were I'm launching the terminal or just my term the I only have to change one line now to change my terminal emulator in the script I just go in here and replace s T with X term boom I'm done so that is the great thing about setting up variables so if you repeating a lot of stuff in your script is set up a variable for it now why don't we like do a real world example of me creating a script that actually does something I'm gonna just come up with some thing so what I did is I created a directory on my system called test and if I do LS you will see I created six subdirectories inside the test directory and if I seed eat into one of these like the blog directory subdirectory here do an LS you see I have some markdown documents in here these are documents that are written in markdown which is you know plain text it's this kind of thing you would typically edit in a plain text editor like Emacs for example anyone the CD back into the above directories because the test directory is really where I want to do some work so in the test directory I have those six subdirectories what if I wanted to create a D menu script that let me choose between these six directories and then once I choose what directory I want to work in that D menu script shows me all the markdown files in that directory and then when I choose the markdown file I want to work with it launches itself automatically in Emacs or whatever text editor I want to use now it's kind of complicated it's not I could do that pretty simply using a simple bash script oh basically what I want the D menu script to do let me show you a basic deep menu script so this is me launching D menu where it opens up a list of config files that I could potentially edit that's kind of what I was wanting to do here at stuff instead of config files I wanted to list these six directories in that test directory I created and typically I would do that is doing something like you know just listing them out with well I would I could just type them out if I wanted to log contact forums merchandise videos and then in the list I could do something like that but that's kind of tedious right because what if I add more directories here what if I delete directories then I'm gonna have to edit the bash script here I'm gonna have to add those directories or delete those numerous trees in this list I created well there's got to be a better way and there is what I could do is run an LS command here in the test directory and it lists those well I could have the bash script do it LS command and it will give me these directory names but it no will also give me the permissions it'll also give me my username the date I don't need all of that stuff but if you know a little bit of the command line stuff and this is gonna be complicated but I would run this command here so I'm going to run the LS command slash bin slash LS what I'm doing space - D do the LS command but only show me directories I don't want to see files right I just want these six directories I don't need filenames I also am cutting out some stuff basically the cut command is finding everywhere there's a space and then and then it's going to show me the first field I like that list I can work with that list it has a trailing slash if I wanted to I could you know get rid of the slashes too and just have the directory names without the slashes I kind of like the slashes though because in the demon you script when in those directories show up with the trailing the backslash it'll be obvious that I'm dealing with the directory in the script I'm gonna leave it so I'm going to copy this command because that's what I want the script actually executes I'm gonna copy that and I'm gonna go back here and I delete that list and instead have it run then now for this to actually execute no this options list actually executes the LS command and do all this we actually do need to put a dollar symbol in front of the parentheses in this case of course this is not actually going on we can't run the script just yet thank you and this is just creating options equals it's a variable write options equals this command then I'm gonna go down to the next line I'm gonna have it run this command echo which echo basically print on the terminal which is where we're gonna execute this print this line so echo and I'm gonna do another symbol I'm gonna do the swirly looking brackets here options I want it to echo this options command let's save that and then I'm gonna go back to the terminal let me clear that and run it again and there you go it is running the LS command and then it's doing the cut command and giving me a list of directories with the trailing slash behind it those are not the right directories though why are those not the right directories it's because the new SH file is in the home directory and again I really wanted LS command to be run inside the test directory well how do we do this well we go back into our shell script and in options we want it to CD into test first so CD into in my case slash home slash DT / disk space and then run and and space and then run the LS command I save that and then execute that script again there we go so I like that so about blog contact forms merchandise videos those were the six directories that I wanted to appear in this list now we worked with variables before I mean we created one this options you know why don't we create another variable while we're at it because quite frankly that is kind of sloppy slash home slash DT slash test why don't I actually make a variable for that how about I do my directory or my dir equals and then in quote single quotes or double quotes it really doesn't matter slash home slash DJ slash test and then in the quotes and then I can go back down here and delete slash home slash DT slash test and instead do a dollar symbol and then once again the the brackets and then inside the brackets my directory I save that execute the script again it works exactly the same but I the only thing is I swapped out you know home DT test or this variable my directory now how do I get this to launch in demon you you know and you guys know what demon you looks like this is demon you you know it's up basically a run command launcher is kind of what it is so but I wanted to take this list of directories and give me that inside demon you as options how you typically would do this if I go back to the terminal D menu is typically run with options like this leave menu space and then I'm gonna give it these flags - I - P for prompt and then what do I want the how about my directories I hit enter right now nothing happens let me just control see to kill that a demon you doesn't actually do anything it's because we really didn't type anything into demon you demon you wasn't going to run anything right there but we could pipe something into D menu for example if I wanted to I could you know what pipe this list right here so if I'm not even the whole list I could just do a partial but let's do that and then I could do the pipe symbol right there and then if I wanted to pipe all that into that and then watch what happens now I actually get something I have my directories and then the prompt but it really didn't give me that list I probably needed to wrap those in quotes I'm sure that's probably what I needed to do let me rerun that one more time and then the list let me actually wrap that in quotes I should have known better than that I run that I still not giving me the proper list here let me think about this problem for a second you know what because that's not an actual command this list I probably need to run something like echo and then in quotes the list pipe it into demon you there we go well that would work something like that and I again anything that we can do you know at the the prompt here we can actually put in our bash script so let me go ahead I'm gonna get rid of this echo here and what I'm gonna do is I'm gonna create basically our demon you prompt and I'll call it choice equals dollar symbol and then the command and basically just do that echo command that we just did alright so basically I just put that command that we'd run in the terminal so we know it works here let me save this and then you know what let's run our show script new SH and see what happens alright the demon you launches I've got the prompt you know I could type here if I wanted to type something and then it lists our directories but know if you noticed because they're all in this pink background that is one directory it thinks there's only one directory and it's called about blog contact it's all one word because to be a proper list here in the bash script they need to be on their own separate line I'm actually just gonna this is just a quick and dirty script here let's just go ahead hit enter after each selection let's save that script let's rerun this demon you script here ah I see now we actually have six different options we have about blog contact alright so now we're getting somewhere the only problem is again I would have to manually edit the directories in that list every time if I went with that is there a better option absolutely so this options equals and then this LS command which also equals that is actually an array an array is basically a list of stuff it is a basically those lists that this options list is an array it's a list of those directories inside the test directory and you can work with arrays in quotes I would do dollar symbol and then let's do the brackets again and then options so we're gonna call on options here and then in these square brackets I'm going to put the @ symbol what does that mean it means echo print out everything in the options list that's what the @ symbol is give me all of it everything that's a part of that array then pipe that into D menu run D menu with these flags I and P and then the P is for prompt what do I want the prompt to say I want it to say my directories colon space let's save that hope this doesn't get too complicated but hopefully you guys watching me just kind of go through something on the fly hopefully you kind of see what's going on let me run that script and it works right it gives me everything in this options array right it echoes it out pipes it into D menu makes D menus prompt save my directories colon space if I wanted to I could actually search for something I could start typing you know and once it gets to the last thing that that fits what I'm typing you know it just goes straight to it now me if I hit enter right now nothing happens right nothing's returned that's because we haven't told daemon you what to do when we choose something in that options array what do we want it to do well why don't we create a if-then-else kind of statement for example if the directory is called about do this if the directory is called blog do that so a basic if statement in bash will be something like if let's do the square bracket and space make sure you add a space and then we're gonna do a quote dollar symbol choice so basically if one of our choices space equals space and then about now the slash so if one of the choices is called about with the slash because you remember we have the slashes behind the names and then for space again and then the trailing square bracket and then do a semicolon space then so if this is true then do this echo it works all right matter of fact we could just do it if then and then to close it out do fi the reverse of if I save this document let's execute the script see what happens so if I choose blog in the list hit enter nothing happens of course let me execute the script again but if I choose about let's see what happens notice in the terminal I get it works exclamation point so that is if and then let me run that one more time I'm gonna execute that script about with the slash what if instead I wanted to because it's a part of an array what if I don't have to actually call on it by name and I could actually call on it and this way right here dollar symbol and then do the curly brackets inside the curly brackets we're going to they in the choice array square brackets give me the very first thing which they're numbered starting with zero because about is the very first thing in the list it should be the zeroth thing in the array the very first thing I'm gonna save that let's execute the new dot s H script again alright now if I choose something not about say contact nothing happens because in the script we didn't tell it to ever do anything if I choose contact but if I choose about it should echo it works it didn't do anything so just calling on choice doesn't really give us anything I think what I need to do oh it's not actually choice that I need to do so it's not choice there let's see if options let's pick something from the options array it's not the choice of race see this is why we do everything we leave all the mistakes on camera save that now if I choose blog now this has too many arguments ok I rerun the script and choose about do many arguments so it's not the options array you know what I think I need to do let's set up a another variable basically to make sure that this is an array that we're choosing from ARR for array equals and then what I want it to equal to is in parentheses dollar symbol options I want you to take all everything from that options list make it an array and then if choice equals that array the first item from that array then echo it works save that let's run the script first let's see what it does if I choose something that's not about nothing happens that's what we wanted to see now let me choose a belt and see what happens it works well that's working so again it's kind of a quick and dirty on-camera kind of hacking bash script right and I like to leave mistakes in my videos those of you who the channel I would see you guys see me make mistakes and then fix it I think that's important cuz you're not gonna get everything right the first time you do things I want you two guys to see I don't get frustrated I just work it out I just keep hacking on it until I figure it out alright so there's six items in that list though we only told it what to do if the very first one was selected we didn't give it any other instructions what if you know the second third fourth fifth or sixth directory is selected instead of the first well instead of if then we could do if then do this and then the next line where I'll do LF else yes so if we choose the very first option do this then elsif choice is the second thing in the array which would be number one one is actually the second thing because the numbering starts at zero then do this will tell it to echo it does not work let's get rid of the s sorry if I save that let's execute it run the script first of all let's choose something that's not either the first or second item nothing happens that's what we expected now let's choose the very first item about it should say it works perfect from the script again choose the second item which is blog and it says it does not work alright so basically if we wanted to do something different with each of the six items I would have to do if then Elif then and then Elif again and you know what this is save time just doing a quick copy and paste job so basically I'm doing yes and then statements for each of the six options and then I'm gonna say echo you know what why don't you echo the name of the directory I choose if you pick the first directory and go out the name of the first directory all right so I completed the list so if you choose the second thing in their array for example I want to print out the name of the second thing in the array which is the directory names themselves alright I'm gonna save that let's run it all right so I'm gonna run the script and whatever directory I choose it should print out that directories name in the terminal now and it does alright the script we're starting to get somewhere the only thing is I don't want to run this D menu script right where it lists these directories what I wanted it to do I wanted to dallisa these directories and when I chose the directory I wanted to give me the markdown documents in that particular directory I chose and then let me open whatever markdown file and whatever text editor I wanted to run it that's a complicated script and I've already been at this script and making this video for awhile so to speed things up I'm going to make this a little bit quicker so what do I want this script to do you know what I wanted to do I want it to open up my text editor which is Emacs I tell you what why don't you open the directory that I choose inside Emacs well you guys are like Emacs this a text editor how is it going to open up a directory in the text editor well Emacs also is a file manager as well it has a file manager called dear IDI actually built into it so if you open a directory and Emacs it will actually open up that directory so I'm going to say hey if you choose this from that array open up Emacs I'm gonna use the Emacs client give it this flag - see now what's interesting here if I you know just do something like you can open up Emacs and then you know open up Emacs at this location there's something we need to take into consideration here for one thing I have it open up I haven't opened up the very first directory in the list which is about saying Emacs open up the about directory well what about directory about remember this script is being opened up in home in the home directory the about directory I want to open up is in home slash test lash about so remember I did the variable at the beginning of this script my directory equals home / DT / test well what we need to do is actually say a Emacs burst I want you to open up the path to my directory now the path to my directory does not end in a slash so I need to I need to either add a slash in between my directory and the array or what I probably should do is just add a slash to the variable here then that makes a little more sense now I think I think that would work one other thing just saying launch Emacs doesn't work you actually have to give it a command execute exe C execute Emacs at this location let's save it and actually run this if I choose about let's see if it opens up Emacs file editor at that directory location and it does that is Emacs that just launched that is Emacs directory editor there it's file editor and it actually opened up and you see at the top slash home slash T DT slash test slash about and there's two markdown documents actually already in that directory so how cool is that all I'm gonna do is actually do the same thing you know I could actually just you know do some copying real quick undo that alright so now I've got this where it should open up any of the directories that I choose at their proper location inside MX's file manager first thing I didn't save it so let's save the document and then let's execute the shell script here in the terminal and let's see if it would open up I don't know how about the videos directory inside Emacs and it does and I've got a bunch of markdown documents in that directory I think that's all I'm gonna do with this script today again this was just an example of you know some kind of thing you might want to do with a bash script I mean again it's just a maybe kind of a contrived example but there will be things you want to do on your system that sometimes you need a little scripting for and again I hope this inspires you a little bit I'm sure some of you guys are probably watching video thinking man there's this one thing I've always wanted to do and I didn't know how to do it I know it's possible if I knew a little bear scripting man just get in there and play now that I've shown you a little bit of the basics and you know just how to make a simple bash script using variables arrays if-then statements just knowing that you can already do a lot with bash now before I go this show was made possible by Ansem first Chris second Chris Daniel David DJ Donny Dylan George Corby nyan lamda Mitchell Nate Tech Philip Rob Robert Sean Stephanie and Willie they're the producers of the show they are my highest tiered patrons over on patreon without these guys this episode about bash scripting wouldn't be possible Jose also brought to you by all those other fine ladies and gentlemen all those names you see on the screen that help support my work over on patreon sincere thank you to each and every one of you guys if you'd like to support the channel please consider doing so you'll find me at distro tube over on patreon alright guys peace [Music]
Info
Channel: DistroTube
Views: 19,603
Rating: 4.8742514 out of 5
Keywords: bash, shell, script, Linux, terminal, programming, variables, arrays, if statement
Id: xhI1qXUrAHw
Channel Id: undefined
Length: 38min 51sec (2331 seconds)
Published: Sat Oct 26 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.