If you ask someone to recite the alphabet, they are essentially using a loop to do so.
Or ask them to list the books they have in ther library.
There are countless times we use a loop and not even realize it.
In programming there are several ways to perform a loop.
Previously we created an array 'MyFriends' with 3 elements, and we know how to display a single element, but what if we want to see the whole list? Here is one way to do it.
Since array indexes are numeric, we can use a for loop ...
for ((i=0;i<${#MyFriends[@]};i++)); do echo "${MyFriends[$i]}";done
Alex
Harvey
Billy Jo
The structure can be interpreted as follows:
The loop structure is enclosed in double paratheses (( )).
We need to double-quote "${MyFriends[$i]}" to render any spaces in an element.
Populating an array in a loop is a common task.
Use the for loop when you know the number of times you want to execute the commands.
The while or until loops are used when you have a logical condition that needs to be met, or don't know how many times you want to execute a command.
While loops are designed to run while a condition is satisfied and then terminate once that condition returns false.
On the other hand, until loops are designed to run while the condition returns false and only terminate when the condition returns true.
An until loop (or do-while, repeat-until) always executes at least once, whereas a while loop may not execute at all. The difference is when the condition is checked:
● until loops check the condition after the code block runs
● while loops check it before.
x=5;while [ $x -lt 10 ]; do echo $x;let x+=1;done 5 6 7 8 9
x=5;until [ $x -gt 10 ]; do echo $x;let x+=1;done 5 6 7 8 9 10Piping