 Well, it's that time of the week again. It's time for Chit Chat Across the Pond. This is episode number 761 for March 4th 2023 And I'm your host Allison Sheridan this week Our guest is Bart Bouchotte with another installment of Programming by Stealth. How are you doing today Bart? I am doing good The I've ended up with different show notes than I had planned to have and slightly different than what I promised But I really like them. Does that make it better? It's good Yeah, yeah, well, we don't know that it's not right It's not what you thought it would be, right? Yeah, and I'm I have also learned that there's a few more things I want to teach you because I was doing I was trying to do examples that didn't use anything we hadn't done and I realized that we're missing some fundamental pieces that I completely slipped my mind like say the ability to do mathematics We forgot that so that's that's not on the agenda for today But that is I have added that to the I've started to create a list of silly things I forgot early on and we did boolean stuff But we didn't do the obvious next step, which is math So that's you know, you do need to do that from time to time, you know add one It seems like I should be able to do that, right? We've been talking a lot about the fact that I can't add one to the number of podcasts I've done So yeah, that's a good one to do. Yeah, the other thing I'd completely forgotten about on my mental map Is that uh bash doesn't only have arrays. It also has dictionaries, which it calls associative arrays So trying to cram arrays and loops into this episode and then also get associate of arrays in was a terrible idea So all arrays are next installment But the other thing I had forgotten was quite how many loops bash has Four we're going to learn about four types of loop So that is sufficient I think and the great news is I like the good loop. They all They all Provide a nice way to do a common thing So in theory you can simulate every loop on planet Earth with a while loop. That's true in pretty much every language But it's often you get much nicer code when you use different looping constructs and you get code that reads more like English And that will make future you very very happy Because okay, so you can do it in a way that's not wrong But it's not as elegant and good looking and logical looking as it could be Yeah, which I would which the fancy pants word I would put on that is maintainable Right Yeah, because I don't like it and he was oh you're just wasting time I was like no I am making this code maintainable and I promise you in five years times when there's an emergency We have to fix this in two minutes. You will be very thankful. This code is maintainable I get it grumbling. Okay, fine. It's an investment then. Yes, it is not a waste of time an investment. Anyway, I'm getting ahead of us so We will be learning about while loops until loops for loops And something that's sort of kind of a loop because it does go around forever a select loop and I have Never come across anything like a select loop in any other language Um All four of these loops have a very very similar structure, which is very pleasing So if you remember when we did if there was the if keyword to start a conditional and then we had the then elif else and fee commands to control the conditional Sort of define the code blocks. Well for a loop you have less that you need to define You don't have this concept of an and an else, right? So what you have is the four loop kinds and then they all they all four of them use do and done So while something do done Which again, it's clean. It is clean. So what so while whatever do done Until whatever do done for whatever do done Select whatever do done Okay So the while loop is the most generic loop while some condition is true Keep doing these commands Right, so you're going to have while and then you're going to have your condition And then you're going between you're doing you're doing you're going to have a list of things to do And as long as the condition evaluates to true, we execute the commands We check the condition again We execute the commands we check the condition again and we keep doing that as long as the condition is true So could you make an educated guess as what an until loop might be for? Until it's false Or no, no as long as it's false As long as it's false or until it becomes true So a while sounds backwards to me, but okay Well, it's an inverse right the and until is the opposite of a while So a while does something as long as something is true. So while something is true. We keep doing this Uh an until loop is Keep doing this until something happens So the most common form of until loop is to wait for something That takes time and you don't know how long you might have an until loop that just keeps checking You know check wait five seconds check wait five seconds. Oh, thank goodness. It's finally true now I can continue my code Or okay, that makes sense asking the user for input I want an integer. No really an integer. No really an integer. Oh, thank goodness, right? So Now I'll be able to remember it. There you go the for loop is for Methodically making your way through a list if you have a list of things you have to process a for loop is probably what you want Because a for loop will start at the start of a list work its way through and then finish and the last one the select loop is It's an infinite menu It presents you a list of all the possible options lets you choose one Executes the loop for that value and then gives you the list again And it will keep doing that until your code tells it to stop So if you have it specifically for user interaction Specifically it is a user interactive loop So it is used in terminal apps that present you with the menu, you know, they're not as popular these days But you used to log into something like Before all of our switches and routers had web interfaces You would tell that into them and they would give you this menu You know choose one to set your dns server to choose two to do whatever And then you would do whatever and then it would just ask you now What do you want to do and it would give you the same menu again choose one for your dhdp. So, you know, whatever Those are what a select loop is for So basically we ask the user we do what they said and then we say hello What would you like now and then we keep doing that? So cool So as I've said the structure is always the same Loop command followed by whatever arguments that loop command needs followed by a do Then as many commands as you would like followed by a done So that is and they're all that shape, which is very pleasing that they're all so similar The other thing we have Is that all three all four of them support two flow of control commands which They exist in javascript and we have talked about them and I adore them But I don't know if many people use them They are continue and break. Do you remember what continue does in javascript? I don't remember the context for it So in a loop know what the word means in a loop in javascript Whether it be a while loop a for loop a for each loop If you use the keyword continue in javascript, what does it do? I don't remember Okay, but thankfully it does the same thing in in in bash, which is nice for people to remember So when you're in a loop you have a bunch of commands The continue command will skip everything else left in the current loop And go on to the next iteration So it won't exit the loop, but it'll just jump to the next cycle So it's very good for skipping things So imagine you're looping over a file and you want to skip blank lines at the top of your loop you could say if square bracket square bracket minus z my variable named square bracket square bracket Do sorry if then continue fee That will mean that you go into the loop you say is this an empty line? Yes, it is skip on to the next iteration And then all the code below is is ignored for your empty lines It's much easier than putting everything else in an else statement Especially if you have five or six checks to do right? What if you're checking for empty lines you're checking for comments You're checking for something that's invalid if you have lots of different checks If each of them is just a simple if statement where they continue Your code is much cleaner than if this goes wrong else if this goes wrong else if this goes wrong You end up with some really horrible mess otherwise So the continue command is fantastic for short circuiting a loop around a loop And the break we weren't talking about conditionals. We were talking about loops And all your examples of continue were just in a conditional Okay, so you want to loop through something to process it Right, so you're going to go around the loop An amount of times right could be could be 10 could be 100 So you're going to have say 10 lines of code for do what I want to do On those 10 lines of code you're probably going to have some conditionals right if Whatever i'm processing is like this do this otherwise do that If you meet a condition that says i'm done here I don't need to do any more work in this pass through the loop Then you would say if whatever the heck is going on continue And I will just jump you to the next thing Okay, I think I see it now. Got it. Okay. Okay. Now we do have examples So you will see these in action and continues big brother is break It just means I am so done here I'm leaving the entire loop. I don't care if I was supposed to go around another 100 times We are leaving this loop. This loop is over So break is a real We're finished with this loop. I So it will definitely require a conditional to trigger break Yes, run into this situation Abort abort. Yes, exactly. So yeah, so continuous like Stop this one And break is just stop If that helps, okay yeah so Let's start with the while loop because it's the most generic And it's possibly the one I think you will tend to see most So just like with the if command You say while space and then you Basically provide a command and it's the exit code of that command will determine whether or not the body of the loop gets executed So the stuff between do and done only gets executed if the command after a while Gives you a successful exit code Which is zero Which is zero exactly so Get ready. Okay And it will so it will the condition is checked So the command is executed and we check the exit code If the exit code is success, we do the content of the loop If the exit code has failed, we skip the loop. We never we execute the loop is zero times, right Assuming we get a success on our first attempt We execute the code of the loop and then we go back to the top and we run the check command again So whatever was after the while we run it again We see whether we've got another success if we've got another success through the loop We go again and we keep doing that until there is not a success And then we jump to to beyond the done So then yeah, we continue executing our script after the end of the loop In other words after the done Make sense Yeah, yeah, perfect so Possibly the most common use of the while loop Is for reading a file's content line by line Because you don't really know how long it is. So a for loop is a very bad fit Whereas the while loop when combined with our friend the read command that we've seen before will Cycle through line by line by line Until there's no more lines So we have seen that read Can be used to read from standard in And so if standard in hasn't been jiggered with for want of a technical term Then standard in is connected to the keyboard. So when you ask read to read something from standard in it comes from the keyboard But if you jigger with it standard in can be anything So the pipe command for joining two terminal commands What it does is it takes a standard out From the command on the left, which would normally go to the screen It diverts it And turns it into standard in for the command on the right So what would normally the keyboard is not the keyboard It is in fact the output from the previous command And so we can use a read command to pull The content of whatever was whatever's on the other side of the pipe And what we didn't really say when we used read for reading from the keyboard, but it's kind of implied Is read goes one line at a time you hit enter And that took the value and brought it into your script because enter is the end of a line So if you use the read command and you pipe it five lines of text The first time you run read it will read the first line And then it will stop and it will give an exit code of success If it did read a line or fail if it didn't read a line So can you see how a while loop in combination with a read command can let you cycle through a file? Yes, yeah, that makes sense. So that is the single most common now. There is one little caveat here By default because it's expecting you to type stuff in on the keyboard by default the read command Obeys escape characters So if you want to type into the input to read A new line character you can say backslash new line and it will accept that as input instead of ending the line But if you're reading the content of a file It could contain actual backslashes so you want to tell bash to Read without sort of to repress in my mind. I call it repressing the escape character So the minus aura flag basically means I want the content of this file and I don't want you messing with it I don't want you turning backslash quote into quote or backslash new line into new line Just give me the actual characters that are in the actual line of text, please Okay, all right. It's just a habit you have to get into read minus or So let's stop being all hand wavy The first of really quite a few examples in this installment. I went up as far as the letter g So I don't know how many well a b c d e f 2 or yeah more way more than five anyway So our first example, we're going to read as a content of slash etc slash hosts Which is a file that exists on every flavor of linux on the mac, which is why I've chosen it Um, it's often doesn't have all that much in it. But anyway, um In there is where you get to define mappings of ip addresses to names that exist even when dns is broken And the file allows the octo sort for the pound sign to be used as a comment So we're going to write a little script That prints out the content of the host file, but it ignores comment lines Which gives us the opportunity to play with our continue command in real well, okay So you will find the code in pbs 146 a dash while That sh So we have our usual shebang line then we echo at a message your computer has the following host entries And then the first thing we do is we cat the content of etc hosts into a pipe And on the right hand side of the pipe We have a while loop So we cat etc hosts pipe while Read minus or and then we choose the name that that we want to read the line of text into And so we are going to read the next line of text into a variable named hosts entry Okay, so just a reminder. Can I say back what that means what you just said? So cat is basically saying get the contents of this file Correct And it's in the file we've chosen is slash etc hosts and then use the pipe so that it becomes That the text that you just pulled from that file becomes the text that's standard in To the while loop Which is going to read and we're going to say minus r because we wanted to repress thinking about escape escaping a special character so that it listens to it and we're going to put all of that into Each line will go into a host entry correct, they be added to host entry or They become host entry for that instant in time For that pass through the loop until the next time you call read right? So every time you call read it replaces host entry with the current with the next line It got and the next line it got and the next line it got and as long as it gets lines It does two things update the variable give an exit code of success update the variable give an exit code of success and when it runs out of input It doesn't update the variable and it gives an exit code of fail Which will end our loop. Okay, so I should I should have Said more than in my description because I didn't understand that as while read is you said read looks at line by line So it's not reading the whole etc host file. It's reading at once Over and over again until it runs out of lines to read and that's correct. It's false The exit code of one correct Yes, okay, which has the effect of ending the loop. So in effect, so we started a while loop Yeah, so everything between do and don is going to get executed once for each line in the host file And we can access the content of the line with dollar host entry So the first thing we do after our do Is we check if the line is empty because we don't want to waste our time printing an empty line So we say if square bracket square bracket, and then we use the minus z operator for checking for emptiness Or for checking for zeroness, I guess if you want to mnemonic Did we already learn that minus z means? We did We did we learned about it last time but we learned about a lot of operators So I would I imagine you you will end up looking back at the previous installment as a little crib sheet And I imagine you'll make friends with the ones you use most often because everyone's coding style is a bit different So everyone's going to make friends with different operators Uh, I I much prefer a minus z to checking if something's equal to the empty string. I I don't know. I just prefer it that way It's not wrong or right, right? It's This is how my brain does it so if minus z Dollar host entry says so for this line that we just read because host entry was the variable name that we created for the One line we just sucked in from etc host If minus z meaning if this this one line is empty Then and then then and you've got to continue So it says don't even do the rest of this thing start out go to go to the next line Bing Bing Bing so we've short circled the rest of the loop Okay, the next thing we do is we have another statement So this time we're going to take Host entry and we're going to echo it so echo just means printed out and then we use the pipe To shove the content of host entry into the egrep command which lets us check for a pattern And the pattern we want to check for is starts with the octo-sorp symbol the pound symbol Whatever we're calling it today the hash symbol. We haven't said that word yet So if you're wondering why a minus q Well read it out loud because they haven't they don't know that there's a minus q It says if echo dollar host entry pipe egrep Minus q and then the starts with octo-sorp. Yes So normally you would use grep to show you to show you the lines that match a certain pattern But we don't want to print out of the screen the result of this grep We just care about the exit code And grep will give exit of success when it finds at least one thing And fail when it finds nothing So minus q says don't bother printing it out. I don't care what lines you found I just want your exit code. So it's q for quiet Oh, okay. Okay. So you're saying egrep would have printed it out It would have printed it out, which is very annoying this I know because the first version of the script I forgot the minus q And then I put it back me up again. What is the purpose of this script? This is going to be to find everything that isn't a comment So there was a host name Precisely so the actual entries in the file. So an empty line isn't an actual entry And a comment is not an actual entry Precisely. Okay. And this was a way for me to show you the power of continue And to show you the power of loops. So I spent a bit of time picking this example So if we haven't fallen through either short circuit Then we arrive at the last line of code inside the loop Which is simply echo a star sign to make ourselves a markdown style bulleted list Done or host entry done So if you run You will see probably on a new mac you'll probably see two entries. Uh, basically an ipv4 Actually, no, you see three entries an ipv4 for local host an ipv6 for local host And then the broadcast address for broadcast host I have local host broadcast host and local host again Yes, so colon colon one. Yeah, that's that that is the world's shortest ipv6 address That is literally the shortest ipv6 address So there we go. So that is an example of a while loop in its most common form Reading through lines of text from something So in this case it was from capping a file Let me describe it from the top again because we didn't really we didn't actually finish it very much But so you said echo your computer as the following host entry. So that's what we're going to see spit out on the screen Then we did the catetc host. So we get we get the file and we pipe And we pipe pipe it into while read-r host entry So it's going to pull that one line Then it's got to do and a done at the big picture But inside that we are we want to skip empty lines So we do the if minus z dollar host entry. So if it's nothing then continue So go to the next line We have another if then which we didn't actually describe the if then but the if was to uh, take a look at the host entry and using egrep Quietly find out if it has an octo-thorpe at the beginning if it does then continue Otherwise the next thing that's going to happen. We don't have an elif or anything But the only other thing it can do is echo Uh and a star for the markdown dollar host entry perfect Okay Right. So again, just I didn't have to make that file executable to run it because I did Because I did before zipping it Okay, thank you Yes So just to draw your attention again I'm going to keep saying this because it confuses me and I've been writing these scripts for years. Therefore. I know it's confusing our listeners So the read command we pass the name of the variable host entry When we go to print it or when we go to echo it We have to say dollar host entry because remember dollar means value of So i'm just repeating that for repetition sake. So it's just value of yep as soon as I saw it I went way up. Oh, right But I had they argument my head Yeah I'm also just drawing attention to the minus z from last time. It just means check for an emptiness basically So minus z will work with arrays, which we haven't met yet and strings And I believe it also sees zero as empty. So it's kind of like a a catch-all for nothing powerful Yes, it is a a powerful idea of zeroness And then of course the continue command is the other thing I want to draw your attention to um and Oh, I've seen a terrible typo here host eternity. I can't pronounce my typo You got it good because that damn loss on that one And if I'm going to make a note to myself that I should put a link in the show notes here to detain me the terminal episode on eGREP That probably will help people who have not done take me the terminal first So the eGREP command accepts from standard in Some text And it checks it against a regular expression in pcre format So the hat symbol means starts with and then the octo-sorp means the octo-sorp So we are literally checking to see if the host entry starts with The octo-sorp Right So I've spent a lot of time on the while loop Because it's the most common and because all of the other ones are very similar So we don't have to spend nearly as much time because I can just say Like the while loop So let's immediately jump into our first new friend. It is going to be the until loop So until is exactly the same as while not But I find while not hard to read So I will always use until in languages that support it But it is it is literally a while not loop if you want to think of it that way And the most common use of while not is for us squishy humans so The next example I've been a bit arbitrary here and people will complain at me slightly that names can have dashes in them and stuff But I was I don't want this to get too complicated. So the script example b Is going to expect the user to enter a name and then it's going to greet them by name And it's going to check that they really have entered what it considers to be a name And to make it a realistic example We're going to say you can either give me the name as a command line argument Or I will make you type it in But no matter how you give it to me if you give me garbage, I'm going to ask you again So if you pass it as the first argument and it's not valid I'm going to ask you if you don't pass any arguments I'm going to ask you If you pass me the correct name as the first argument that I won't say anything The script will not prompt you. It will just greet you. Is that does that make sense? Yeah, yeah, I think so Okay, so again, it's pbs 146 b dash until that s h We have our shebang line And the first thing I do is I simply assign a new variable named name And I give it the value of dollar one in other words the value of the first argument gets put into a new variable with the name name And that may or may not be empty right because there may or may not be your first argument It doesn't matter So we then go to the until loop where we are going to keep asking for a valid name until we get one So we say until And then just like with the while loop we need to give it a command And what's going to matter is the exit code of the command But in this case if the exit code is fail We do the loop and if the execute is success we don't Do the loop it's an opposite. It's an upside down world So again, we're taking our name variable and we're piping it into egrep And the pattern we're looking for is starts with An alpha character. So not alpha numeric Alpha, which means you can type in accented characters. I was friendly enough to foreigners to do that Uh Followed by one or more of so the plus symbol means one or more of followed by End of the string. So start of string one or more letters End of string is the pattern for a name Okay, so the so the artist's formula known as prince wouldn't be able to do this but Yeah, as I say, I it's not realistic It's the point is to have a condition on the input and that's like that this will do So okay, so so the first time you run it it's going to be false because you haven't yet done the do loop Well, it might be true Right, if you passed me in a successful if you've passed me in a valid name then the first time through the loop But we'll not go through the loop Okay Okay, that's right because you can add the argument after you say to run the command Exactly and we will have taken it and put it into the variable name So when we echo dollar name It will already be valid. We will pipe it to egrep egrep will say. Oh, yeah, I find this pattern Until we'll say oh, you succeeded then I shall do nothing because remember until is upside down world success means fail so Think of it like 1984, you know pieces war Whatever you want to put anyway So insider do we simply have read minus p. What's your name? And we read it into the variable named name. So minus p means prompt So in other words, we will type the text. What's your name question mark space and then you will have to type in your name And it will go into the variable named name So this is straight from why doesn't name have a dollar sign on it We are we are specifying Where to go we are not saying give me the value off So at the beginning of this uh little script, it says name equals dollar one But that's only that'll only do something if it got a if it got a name Well, okay, well either way it could contain an empty string is what that means So name either contains some text or the empty string, but name does exist But you can write over name Correct. So that's what we're doing. So read minus p is going to write over name So read expects as its first argument. Sorry. Yes, this first argument It expects the name of the variable to write you so we are writing to a variable named name Okay What's the minus p again? It's the prompt. It's the bit of text that will appear before the blinky cursor Okay That's it's so backwards you're saying read Something that I'm about to cause to exist Minus p prompt. What is your name that then goes into this variable? Yeah, so read what prompt where so read what where I don't see this backwards, but I don't know maybe maybe that helps you funny Read what where is how I think of it Okay, and and that's inside that's the only thing inside the do the do done It's just that read. So then we'll just check. Did you give me what I wanted? Have another go. Did you give me what I wanted? Have another go and until You give something valid another or something that successfully meets the egrep It will keep doing that round and around and around you will go And finally when you give it something that matches the egrep The loop will skip over and you will end up with the echo statement at the end Well, hello there dollar name smiley face And I confirm that it keeps going if you give it a one a parentheses or an accent But if you give it an accent at e It says hello there e perfect, which is why so square bracket colon alpha colon square bracket means any letter including weird ones in other alphabets Which is cool. That's kind of an important regular expression because a to z as a character class Is a valid regular expression But unless you're actually sure that it's really just a to z it's actually not right because accents do exist outside of us English-speaking people, you know I did I did find it funny when you said to take care of foreigners like I'm in I'm in the United States and you're in island. Who's a foreigner? That is yeah, okay. That's a fair point. That's a very fair point Just languages that use accents in names. Yeah. Yeah Okay, so that's the until loop. It really is just an inverse while loop like you could rewrite that code with a while not But like I say until there's so much easier to read until it's valid keep doing it So then we come on to our friend the for loop whose job it is is to do something over a set of things so the Okay, so the way the for loop works is the first argument we give the for loop is going to be the name of a variable The second argument is the keyword in And then all other arguments are going to be what the loop loops over So the first time through the loop The first thing after the in will be put into the variable with the name you gave it as the first argument The second time through the loop the second thing after the in goes into the variable The third time through the loop the third thing after the in goes into the variable And you keep doing that until you run out of things So in is the keyword in it's literally in it's the letter So for space a name you've chosen space in space your values I can read that and I can hear you saying it. What does in mean? it Pretend it's a symbol but It's it's a marker What does do mean? It's it is The language says you must type the characters i and It is the rule. It means to execute something in must be to like to look inside it It's it's it's just a marker. It's just it's a marker that makes english sense for Name a variable in some set of things. It's It's a marker. It's a it's it's a placeholder So we've got something to the it's for something in something. What what is what are the two somethings? What are the which one is which so the first something is the name the variable will have inside the loop The name the variable what variable okay, so the thing Everything after the in is going to be stepped through one by one by one When you're stepping What do you call? The current thing you're stepping Well, the answer is whatever was on the other side of the in huh So for i in one two three four The first time through the loop i will be one the second time through the loop i will be two the third time through the loop I will be three And one two and three will be called the the word that you get put between four and in Yes While you're in that step so four pancakes in Waffles dot html Okay, waffles at html is one thing so the first time through the loop the variable waf pan Ah, what did you call it? Sorry? For for pancakes in waffles dot html. I'm picturing waffles dot html as a whole list of stuff in it Ah, okay, but if what okay if waffles html has the whole list of stuff in it Then you're going to have to do a cat or something to pull the whole list of stuff out Okay, so okay. No, no, no, I I think I have an example for dessert in Pancakes space waffles space popcorn Okay So we're not reading a file here. We've just got a list of stuff Correct. So the everything after the in space delimited Will be the values that go in so it's arguments, right? Just it's a command with arguments So first argument after in yeah Because everything's a command now So actually, yeah, the dessert example is actually a good one So if you say for dessert in pancakes waffles popcorn the first time through the loop dessert will have the value pancakes The second time through the loop dessert will have the value waffles the third time through the loop dessert will have the value popcorn Okay, okay Now in your example So I have some more English to say so The list of arguments Supports shell globs, right? So if you have the command LS Okay, so I'm about to explain So when you have the command ls, you know, you can say ls star And that behaves as if you had typed in every single file in the current directory That's actually what bash does Is it the star character expands into everything that matches it which has actually put there as First file space second file space third file space fourth file So those expansions are called shell globs So you can do for file in till the slash star And till the slash star will actually expand into documents downloads Whatever a desktop whenever picture pictures videos movies whatever apple calls them, right? So each thing in tilde will actually appear on that list And then each one will become the variable one by one It's just the name of that thing Yes, so the thing between the four and the inside that folder just pictures the word pictures becomes Yes, yes, yes So our example is pbs 146 c for files that sh And we have our usual shebang line Echo the files in your home dear colon And then we start our for loop. So for space file space in right so for is Baked in and in is baked in and I have chosen the name file And then what is it we're going to loop? We're going to loop tilde slash star Which bash is going to expand into whatever the heck is in your home directory Which is going to be different to mine and if you're on linux instead of the mac it'll be very different to mine Then we have do Echo our markdown style star space dollar file done Okay I think if I hadn't been reading the show notes what you were trying to explain with four and in would have made a lot more sense Because I kept looking at four file in tilde slash star what? But now that you've explained it now I've Backwardsly caught up if that makes any sense It does so again if you run it you will see it though. It just lists the content of your home directory One line at a time with a little markdown bullet point in front of it. Yay, cool So the other very powerful thing you can do after the in Is you can have a command that outputs a bunch of words And then loop over those there's lots of commands Unfortunately, it's very hard to find something that's cross-platform. So with my real world hat on The modern versions of red hat linux use a firewall called firewall d And it's controlled with a command called firewall dash cmd and firewall cmd outputs its information as space delimited values So I am forever looping over the the output of the firewall cmd command like forever doing four you know service in Dollar sign open round bracket then my command close round bracket and my command would be something like firewall d Firewall cmd minus minus list minus services And then I will get back ssh HTTP HTTPS as the values for my for loop or whatever is enabled on that server Right, whatever the firewall is configured to allow on that server And then I will do something You know, I'm forever looping over the output of firewall cmd So any command that outputs text can be used after the in as long as you use the dollar open round bracket Your command close round bracket, which basically means you get the value of the output of this command And it will just every time it meets a space it'll just say oh, you're the next thing I have to worry about and it will loop through them which is strangely powerful So Like I say, it was hard for me to find an example that will work for everyone whether they're on a mac or whether They're on linux, but I did find a command the groups command lists every group that you remember of separated by a space so Our next example is not named in the show notes. That's a terrible omission by me So the the actual script is going to be d 146 d dash for command ssh Usual to bang line Echo you belong to the following groups colon for group space in space Dollar open round bracket groups close round brackets. So that is saying execute the command just type groups It I tested this because I was trying to understand it if you just type groups in a terminal It just lists all the groups. They were like you said So that's why you're saying for group in dollar Open parentheses groups. So as it spits out this space delimited list Exactly and then every time you go to the loop, it'll be the next value in the list and you will be calling it dollar group So for group in dollar open round bracket groups close round bracket do echo our markdown star dollar group done And that will print out that's actually pretty cool Very powerful. Like I am always fussing around with my groups. Unfortunately. Yeah, so I didn't realize there were so many of them But there are on the mac a particularly more modern versions of the mac There's even more of them anyone that starts with an underscore is a super secret apple group And the other ones are but there's also a bunch of like com. Axel Com.apple.access underscore screen sharing which is also an apple one. Yeah This account has allowed you to now do screen sharing And ssh. Yeah, I don't have I don't have a particular one Sharepoint com.apple.sharepoint.group.3 and .2 I don't do sharepoint Microsoft did that I was going to say there's a there's a non-zero chance you have one drive installed and one drive is sharepoint Okay, that's probably it. All right I see clam a v Clam a v grand don't even ask you don't even ask you haven't done a clean No, no, this is my brand new no, no, this is my brand new m1 mac I did not install clam a v that group came into being somehow. I don't think clam is oh interesting that group exists Anyway, yeah, lots of groups The point is you can so the most common use of while is to loop over a file The most common use of four is to loop over a commands output But it can also do more traditional for loop things So the for loop actually has an entire other optional syntax Called the c like syntax, which I find confusing as all heck Because it does something called automatic Variable expansion Which means you don't use the dollar to get the value of I Which breaks my head every which way But it lets you write something that looks like c code if you squint very hard So if you want to loop from one to five you can in bash and it is valid say for space Round bracket round bracket i equals one semi colon i less than or equal to five semi colon i plus plus round bracket round bracket Do echo the value of i is dollar i done That is valid bash I am not a fan of this approach But it is what do you like about it i is less than five not dollar i i That's i though i gets to do whatever i want or if i could put pancakes in there and it would work Because i'm actually creating a variable and then accessing it twice And i don't have to use a dollar while it's inside the two the double Roundy brackets because inside the double round brackets. You have this magic variable expansion But later on inside the loop's body. It's still dollar i I don't like it. It's also very verbose Because there is a better way. There's a much better way So bash provides an operator called the range operator Which is open curly bracket a starting value dot dot an ending value close curly bracket And it will expand into a space separated list of numbers Between the first one and the last one So the range to to demonstrate it i've put a little table of examples So open curly one dot dot five becomes one space two space three space four space five Five dot dot one becomes five space four space three space two space one so you can loop through in either direction And it works with letters So a dot dot f becomes a space b space c space d space e space f so Why would you bother with four? Bracket bracket i equals one semi colon i is less than or equal to five semi colon i plus plus When you could simply do something like four n in Open curly one dot dot five close curly And then n will become nice and clean nice and clean So as an example, we have pbs 146 e For range s h which is going to print out all of the valid hexadecimal characters by using two range operators So we say four space car space in space open curly zero dot dot nine close curly space Open curly a dot dot f close curly so the first Range will become zero one two three four five six seven eight nine space a b c d e f So the end result is perfectly spaced zero to nine a to f in other words every valid hexadecimal character Now did you have to put a space in between the curly brackets for to get a space there? Yes, otherwise, I would have ended up with a single loop entry called nine a Nine a that's what I was wondering about by the way when he said car He means a variable. He's created called c h a r For character a character. Yeah Now in bash version four, which apple have not dained worthy of sharing with us There is an optional third Parameter, I guess To the dot dot operator where you can say start dot and dot dot step So if you want to go in twos you could have dot dot two Doesn't work on the mac. We are on version three, but don't worry There is a terminal command that can do sequences in every way you care to imagine It's called seq is the command sec for sequence If you do the man page it can do way more than I'm showing you here If you give it a single argument it assumes you want to start at one And count up to that single argument So if you say sec five you get one space two space three space four space five If you give it two arguments it assumes you'd like a range So you if you say sec 10 15 you get 10 11 12 13 14 15 If you do it in reverse it's perfectly happy too. So sec five one will give you five four three two one And if you give it three arguments The first argument is your starting point. The second is your step and the third is your finishing point So sec zero five 20 becomes zero five 10 15 20 So the middle one was the was the step the middle one is the step which is mildly annoying if you're used to writing in bash four But the sec command is portable the sec command will work in all versions of bash and it will frankly work in sh Because the sec command has been around forever So if you want to we if you need to do funny sequences the sec command is your friend it's very powerful And it works on all versions of bash and sh and zsh. So it's portable as well So as an example We have a little a little script called four step range and sh Which prints out the even numbers between zero and 20 by simply saying four n in dollar round bracket sec zero two 20 In other words started zero in steps of two as far as 20 And then we say do echo our little mark down star dollar n done That's fun. That is fun. And I could say I really like the range operator because most of the time you're going in steps of one So the range operator works a lot of the time and it makes for such friendly code For i in one dot dot ten. Oh, it's so nice Okay, so I added in javascript now. I know So that brings us on to our final weirdo friend the select menu loop So select works like four Only instead of it going through everything in order It asks you which one you'd like and then only does it with that one And then it gives you that list again and waits for you to tell it what to do next So the example I have here is Our pancakes example from earlier actually So the example is pbs 146 g dash select s h and it will ask you for what dessert you'd like until you tell that you've had enough Which gives me an excuse to use the brick keyword Which is of course the only way to get out of here apart from the exit keyword, which really gets you out So we have our usual shebang line and then we say select dessert in So again, it's dessert is the name we're choosing in and then come the values So i'm giving it the values pancake waffles Popcorn and then quoted so the space doesn't break everything enough. Thanks And then we have our do So inside the do we have if square bracket square bracket dollar dessert is equal to enough. Thanks Then break fee Echo have some dollar dessert So when you run that you will be asked whether you like pancake waffles popcorn or enough. Thanks And you it will put numbers next to each one automatically and you just type the number matching your choice And then you will get the appropriate echo And if you type four Which is enough. Thanks. It will stop because the break will pull you out of the loop I like it. I like it. I think I would have said, uh, thanks for eating here Yeah, you get the idea, right? It's you know, it's some sort of escape close So I have a challenge for you Oh goody I would like you to write a bash script Which takes Input from the user in some way. Well, actually, okay. I'm gonna be a bit more specific I want you to take input from the user either as the first argument Or by prompting them But I want to get from the user A whole a whole number that is Greater action or just a whole number. I think I say which is good enough. Yeah, and give me a number Then I would like you to print out The table the multiplication table for that number So if you give the number three the output should be one x three equals three two x three equals six three x three Equals nine all the way up to 10 x three equals 30 And so if you run the script again, you give it five. I want the five times tables. You get the idea Uh a little hint The way I would like you to do the math is not the best way It's the way that's the most portable Because it's a terminal command called bc Which does not stand for before christ. It stands for basic calculator And you can either google bc or bing Or you can use man bc to figure out how to make the bc command do your math But the bc command can do the math you need to do here a simple multiplication Oh, okay. Good. So we don't have to do the the we don't have to do the bit that I haven't taught us yet Which is how to make bash do the math itself We're going to let the bc command do the math, but we will learn how to make bash do the math later So if you'd like some bonus credit So by default, I want you to go from one to ten So the five times tables would be one times five up as far as ten times five But for bonus credit, I'd like your script to allow the user to optionally also specify how far to go So if you optionally tell it to go to 20, then I want you to go all the way up to 20x Whatever the numbers that they gave us the first argument So this means figuring out how to get it to put those numbers in as well Not hard coding one times It does so input equals Yeah, so I figured I want to give you exercise in the most important thing So you're going to have to make a variable You're going to have to use the read command to get input from the user You're going to have to deal with command line arguments You're going to have to loop You're going to have to print things out And you're going to have to call a command and use the output of the command for something else So you're going to use the bc commands output for something So that's actually a really good sampling Of everything we've done so far You probably have to check to see if it's a number two You do, yeah So that's again, you're looking you're you're doing some conditional work there of some kind Whether that conditional is an if statement or whether it's part of a loop up to you There's a lot of there's an infinity amount of correct ways to do this challenge But you will have exercised A very big subset of what we've learned This sounds fun And not that hard, but I better get stuck Well, that's the joy of that's why I chose this assignment. It's not long, but it does make you use many concepts at least once And since you haven't had much practice, I would expect this to take you You're going to end up with very few lines of code And probably many hours to get there and that is expected an hour hour per line, right? Yeah, exactly. That is expected and that is normal Uh, so at this point in our journey, we're actually making really good progress But I like I say I realized as I was trying to come up with examples that we have some work to do so Like, you know, they you know, love and marriage go together like a horse and carriage Well a raise and loops go together like you like love and marriage, I guess Um We really do need to do them next and it's been really really hard to avoid using an array For all of the previous installments because arrays are so powerful in programming And we should also learn about dictionaries because they are also Darn useful or associative arrays as they're named in bash world So those two will keep us more than entertained next time because they are very important and I want to do them justice because It's combined with loops. They are extremely powerful and you will definitely need them to to start writing scripts that do real world problems You need to be able to have arrays and associative arrays So that's where we're going next That sounds like fun. I like this stuff part. This is this is really cool I'm having a I'm having way more fun than I thought writing these show notes. Um I I do I've been doing a lot of bash programming But I've been learning about it piecemeal and now I'm getting to learn about it As as a whole say in unit and telling a story and I'm learning so much writing these show notes So many things are making sense to me. Yeah, it's it's actually a very logical a very simple language But it's a bit weird When I say a bit what I mean is heck and lotta weird. Anyway, here we are So I so this is uh is evergreen content, but I think This story will still work with evergreen content. I got a um Masted on toot from a guy who said he was really enjoying. He's starting to to uh do taming the terminal And he said it's great, but Bart talks too fast And so I suggest I said well, you can always go point seven five acts and he wrote back and he went Yeah, okay that helped and then I realized what was wrong Same problem. I had with listening to you on a podcast Smart speed is does not work with Bart's teaching So I've been I was listening I was listening to an episode of let's talk photography and I'm like, oh my god Bart slow down No, no, no, you you just finished the last concept. I don't have it cemented yet. Wait, wait, wait, wait, wait And then I went oh man, I bet I've got smart speed on so I wrote to the guy again And I said do you by any chance have smart speed on and overcast he said oh my gosh, this is so much better Yeah, I'll pause quite a lot I I make heavy use of pauses because I'm used to teaching in real world speed in you know in in actual classrooms Yeah And smart speed goes oh emptiness. We shall have none of that I guess you have a backing track. Go listen to anything you've done where you're teaching and have that. It's horrible I was ready. I was gonna call you and yell at you for why did you why did you do that episode like that? So anyway, I'm glad you noticed also that was a fun episode if it was the AI one The first day I won't I forget. Yeah. Yeah, it might have been All right. Anyway So until we get to meet our friends the array and the associated array Happy computing If you learn as much from Bart each week as I do I'd like you to go over to let's dash talk dot i e And press one of the buttons over there to help support him He does 98 of the work here I'm just the stooge that listens to him and asks the dumb questions If you go over to let's dash talk dot i e you can support him on patreon You can donate via paypal or you can use one of his referral links I really hope you'll go over and help him out in the meantime You can contact me at pod feet or check out all of the shows we do over there over at pod feet dot com Thanks for listening and stay subscribed