Loops#
With the if
/else
statement, we're able to change the "direction" of our code. With a loop, we can repeat code, over and over, based on some other value or range.
The simplest loop to understand is the for
loop. Let's change our code, again, so repeat our message over and over:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
We're telling our script to loop over a range of number, 1 2 3 4 5
(the spaces are important) and then run what is between the do
and the done
. Here's the result:
1 2 3 4 5 6 7 8 9 |
|
That's a bit bonkers, but it demonstrates a for
loop quite nicely.
To understand what's going on here, let's write out the loop in plain English: "for
in
do
this thing until; done
. And when do we reach "done"? In this case, when the list of numbers finishes. Look at the output again:
1 2 3 4 5 |
|
There are five lines. We had five numbers in our list: 1 2 3 4 5
. The definition of "done" for our loop is when the list has ended or has been looped over completely. We're keeping things simple right now.
We can demonstrate this further with another example, which you can just copy/paste to the terminal:
1 |
|
I get the following:
1 2 3 4 5 6 7 8 |
|
So our for
loop iterated over a list which was made up of the files that the ls
file found for us.
So the syntax of a for
loop is simple:
1 2 3 4 |
|
And what is "variable" for, exactly? Why is it there and how do we use it? We can see in our ls
based example, above, that it can be used just like any other variable but only inside the loop's body. You cannot use the variable after you've left the loop (after the done
part.) We can demonstrate this with another update to our script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Which gives me the output:
1 2 3 4 5 6 7 8 |
|
Which means that $i
is the number in the list. It's updated as the loop literally loops over the list. Try making the list of numbers shorter or longer and see what happens.