DEV Community

Cover image for Continuation to Bash scripting: Introduction to Conditional statement and Loop
Kenneth Mahon
Kenneth Mahon

Posted on

Continuation to Bash scripting: Introduction to Conditional statement and Loop

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:

Input

In the example above, the loop will iterate 5 times.

Output

Let take a look at another real world example

Input
In this example, the for loop iterates over all files with the .txt extension, renames each file by changing its extension to .doc

Output
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:

Input
In the example above, (( i += 1 )) is the counter statement that increments the value of i. The loop will run exactly 10 times.

Output

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

Input
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.

Output

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:

Input

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.

Output

bash Scripting is very interesting and very deep.
Thanks for moving with me on this journey. Day 14 loading soon

Top comments (1)

Collapse
 
devopsking profile image
UWABOR KING COLLINS

This is awesome bro.