Continuation to Bash scripting: Introduction to Conditional statement and Loop
Kenneth Mahon
Posted on July 4, 2023
Good Day everyone!!! still on this journey of becoming a DevOps engineer, we will be looking more into loops as discussed in day 12.
LET'S GOOOOO
For loop
The for loop, allows you to execute statements a specific number of times.
For Example:
In the example above, the loop will iterate 5 times.
Let take a look at another real world example
In this example, the for loop iterates over all files with the .txt extension, renames each file by changing its extension to .doc
If you notice, you will find out that all the ".txt" changed ".doc"
While loop
While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.
For Example:
In the example above, (( i += 1 )) is the counter statement that increments the value of i. The loop will run exactly 10 times.
Using the for loop for Nested Loops
The for loop is one of the most commonly used loops in bash scripting, and it’s also an effective tool for creating nested loops. In a nested for loop, the outer loop controls the iteration over the first set of data, while the inner loop iterates over a second set of data for each value in the outer loop.
Here’s an example of a nested for loop in bash scripting
In this script, the outer loop iterates over the values 1, 2 and 3 while the inner loop iterates over the values a, b and c for each value of i in the outer loop. The echo statement prints out each combination of the two values.
Using the while loop for Nested Loops
In bash scripting, the while loop is another powerful tool for creating nested loops. While for loops are useful for iterating over a fixed set of data, while loops are ideal for iterating until a specific condition is met. When used in a nested loop, the while loop can help to automate complex data processing tasks that involve iterative calculations or manipulations.
Here’s an example of a nested for loop in bash scripting:
In this script, the outer loop starts with a value of 1 and increments by 1 until it reaches 3. For each value of outer, the inner loop starts with a value of 1 and increments by 1 until it also reaches 3. The echo statement prints out each combination of the two values.
bash Scripting is very interesting and very deep.
Thanks for moving with me on this journey. Day 14 loading soon
Posted on July 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 4, 2023
July 1, 2023
June 30, 2023