Understanding Nested Loop working in Linux.

In this post, we will look how nested loop works in Linux Bash shell.

The loop works similar to any other programming language.

Nested loop refers to one or more loop(s) inside a loop.
OR, It can be defined as one or more iteration(s) nested inside an iteration.

Let us have a look at a nice example to understand how nested loop works.

Nested Loop Example

Create below script with 2 nested loops inside a loop.

[root@nglinux ~]# cat file1
#!/bin/bash

for a in {1..3}
{
for b in {a..c}
{
for c in {x..z}
{
echo "$a$b$c"
}
}
}
[root@nglinux ~]# 

Output:
Now lets see the output of the above script on bash shell.

[root@nglinux ~]# ./file1 
1ax
1ay
1az
1bx
1by
1bz
1cx
1cy
1cz
2ax
2ay
2az
2bx
2by
2bz
2cx
2cy
2cz
3ax
3ay
3az
3bx
3by
3bz
3cx
3cy
3cz

We can see above how three loops executed and prints the values of all three variables.

We can use the nested loop similarly to accomplish different tasks repeatedly.

Leave a Reply

Your email address will not be published.