By introducing loops into scripts it is possible to repeat a block of code multiple times without having to write the same code over and over again. This makes your code more concise, more readable, and more maintainable.
There are two main types of loops in Bash: for loops and while loops.
For Loops
Are used to iterate over a sequence of values, such as a list or a string.
While Loops
Are used to repeat a block of code as long as a certain condition is true.
3rd Bash script
The third bash script created is:
These loops have varying complexity to achieve different outputs. Unlike some other scripting languages, indentation is not a requirement, but it makes reading code much easier so you should look to follow the syntax of indenting commands when working within loops.
For Loop 1
Loop 1 defines an array called days and gets the parameter x to loop through the list.
A breakdown of the command above is as follows:
· For - starts the loop
· X - provides the variable name
· “${days[@]}” – defines the array called “days” and uses the @ symbol to denote that each value in the array should be iterated through.
· Do – begin the loop
For Loop 2
Loop 2 demonstrates that there is no need to have an else statement as part of a loop and that instead, to trigger an action to execute after the script, the echo command can be used.
For Loop 3
Loop 3 provides an example of how a nested loop may work. By creating two arrays it is possible to use x and y to loop through each array. While not a requirement of Bash, this is where good practice of indenting loops,functions,conditions etc. can make it easier to review code and understand the logic.
By looking at this code, it is possible to understand that our first loop will give x the value of each element of the days array and trigger the nested loop which gives y the value of each element of the meals array and then prints the values of x and y
While Loop
While loops are different to for loops in that they are used to execute commands for as long as a condition is true. In the while loop the value of i is printed to the terminal and increased by 1 for as long as it is less than or equal to 6
The above defines the conditions required for the while loop to execute (i has to be less than or equal to 6)
The loop will then echo the value of i and use the i++ to increment the value of i. As this is the end of the loop, the script will then check if the new value of i is still less than or equal to 6 and start again.