Related
Quick Links
Most programming languages support various forms of looping code lines.
Bash natively supports ‘while’ loops, ‘until’ loops and the most well-known, ‘for’ loops.
This article introduces and discusses all three.
Shutterstock/ jeep5d
What AreBash Loops?
To define this a little better, we should start with the questionwhat are loops.
Loops are a programming language construct, allowing a developer to repeat (i.e.
loop) certain parts, or all, of the code inside such a loop definition.
It is now easy to defineBash Loopsas any loop programming language construct used in Bash!
Bash natively supports ‘for’, ‘until’ and ‘while’ based loops.
Similarly, ‘while’ loops keep running until a condition is no longer true.
Consider thedoa prefix to what needs to be done, and it makes more sense.
A few small changes were introduced to the script.
Note how this time, we are increasing the variableiby two each time.
This done using another coding shorthand, namelyi+=2which can be read asincrease i by two.
One can also writei=i+2in the same place, and it works exactly the same.
We see that we start at1, and increase by2each time we go through the loop, ending at9.
The reason it ends at9is that the maximum value is10.
Thus, after9the next value would be11, which is greater then10and it is thus not displayed/looped.
Note also how the;was removed after the echo line.
In this example, we do the same as our firstforbased loop example.
Here we first set ourivariable, manually, in a separate command terminated by;, to1.
Until such time (i.e.
We can see how the syntax for theuntilcommand is very similar to thewhilecommand.
We keep doing so (i.e.while) until it is no longer true.
Whilst it is true, we print the textyesand pause the loop for five seconds withsleep 5.
Note how each command is terminated with;again.