How to Use Nested β€œfor” Loop in Bash [7 Examples]

Nesting means combination. When one loop is placed inside another, it is called a nested loop. A nested loop is a great tool for handling multidimensional data. With proper outer and inner loops, programmers can quickly iterate through each level of data and do any kind of data processing operation by developing commands inside the inner loops. I will go through every possible approach to using Bash nested for loop in this article. Let’s get started.

What is Nested β€œfor” Loop in Bash?

A nested loop is an approach of placing one loop inside another. The body of the outer loop contains another complete loop. The for loop and the while loop can be nested within each other.

The general syntax of nested β€œfor” loops in Bash is:

for outer_item in [list]
do
    for inner_item in [list]
    do
        [Commands]
    done
    [Commands]
done

For executing commands from the command line interface or terminal, the syntax of one line nested for loop is:

for item in [list]; do for item in [list]; do [Commands]; done; done

7 Practical Examples of Nested β€œfor” Loop in Bash

Nested for loop in Bash can iterate through datasets and do necessary data processing, look for a specific pattern inside multidimensional array elements, and check particular conditions on data. In this section, I have listed some examples related to these. Hope you will enjoy it.

1. Simple Nested β€œfor” Loop in Bash

Bash script can generate a specific pattern on numbers. Two loops nested within one another can do this task. The outer loop controls the row, and the inner loop controls the repetition of numbers within each row.

Here is a bash script that prints each number from the outer loop three times in a row, then moves to a new row with a new value at the outer loop:

#!/bin/bash
#outer for loop to print a number 3 times
for (( i = 1; i <= 3; i++ ))
do
    #inner for loop
    for (( j = 1 ; j <= 3; j++ ))
    do
        echo -n "$i "
    done
    #new line
    echo
done
EXPLANATION

The for (( i = 1; i <= 3; i++ )) initiates an outer loop that runs three times, taking 1, 2, and 3 as values of i. Then the for (( j = 1 ; j <= 3; j++ )) initiates the inner loop that also runs three times, taking values 1, 2, and 3 for j. After that, the echo -n "$i " prints the value of i three times in a single line as the -n option stops to go new line. Then, it goes to the next value of i.

Bash nested for loop printed a list of numbers.A simple nested for loop has printed a list of numbers.

2. Bash Nested β€œfor” Loop in One Line

The nested loop can be written in a single line. It makes the code concise, reducing the line number. Here is a bash script to print letters from the outer loop and numbers from the inner loop:

for i in a b c; do for j in 2 4 6; do echo "$i : $j"; done; done
EXPLANATION

The for i in a b c; do initiates the outer loop that iterates over the values a, b, and c. Then the for j in 2 4 6; do initiates the inner loop that iterates over the values 2, 4, and 6. Finally the echo command prints the current value of i and j separated by a colon. This for loop is a part of the outer loop inside the inner loop.

One line nested for loop printed combination of a, b, c and 2, 4, 6.

3. Nested β€œfor” Loop in Bash to Print Specific Pattern

The nested for loop can generate a specific pattern made of asterisks (*). The nested loops control the number of spaces and asterisks printed on each line to develop a particular pattern.

Here is a bash script to generate an isosceles triangle:

#!/bin/bash
for p in 1 2 3 4 5 6 7 8 9 10
do
    for q in $(seq  -10 -$p)
    do
        echo -nΒ  ' '
    done
    for r in $(seq 1 $p)
    do
        echoΒ  -nΒ  "* "
    done
    echo
done
EXPLANATION

The for p in 1 2 3 4 5 6 7 8 9 10 initiates an outer loop and defines p as an iteration variable that iterates through 1 to 10. Then for q in $(seq -10 -$p) initiates the inner loop where the q variable iterates from -10 to the negative value of the current value of β€˜p’. The seq command generates a list of numbers sequentially. Inside the loop, it prints space without a new line.

Then the for r in $(seq 1 $p) initiates another inner loop that takes values from 1 to the current value of p. Inside the loop, it prints an asterisk followed by a space. Finally, the echo command outside the second inner loop prints a new line.

Nested loop has formed a triange on the terminal.The image shows that the nested loop has printed a specific pattern.

4. Nested β€œfor” Loop to Automate Data Tasks

Proper naming of the files makes the system clean and efficient. Nested for loop enables users to rename files within multiple subdirectories of a specified directory, which automates a long task one by one. Here, a bash script is developed that will iterate over each subdirectory inside a specified directory and then rename the file in a predefined format:

#!/bin/bash
directory="/home/susmit/backup"
for subdirectory in "$directory"/*; do
    if [ -d "$subdirectory" ]; then
        echo "Entering directory: $(basename "$subdirectory")"
        counter=1
        for file in "$subdirectory"/*; do
            if [ -f "$file" ]; then
                new_file="file_${counter}.txt"
                mv "$file" "$subdirectory/$new_file"
                echo "Renamed: $(basename "$file") to $new_file"
                ((counter++))
            fi
        done
    fi
done
EXPLANATION

The for subdirectory in "$directory"/*; do initiates a for loop that iterates over each subdirectory inside the /home/susmit/backup directory. Then the for file in "$subdirectory"/*; do initiates an inner loop that iterates through each file inside the current subdirectory and new_file="file_${counter}.txt" creates a new name for the found file, keeping a counter as a suffix. Then mv "$file" "$subdirectory/$new_file" sets the created new name for the found file.

The nested loop has changed multiple file name.

5. Using Conditional Statements in Nested β€œfor” Loop

Nested for loop helps to make decisions by processing big datasets. For this, one loop is placed inside another loop. Then, an if statement is placed inside the inner loop to make decisions and accomplish the task. Here, a bash script is developed to check whether an array element is odd or even.

#!/bin/bash
# Defining 2D array
declare -A arr=( [0,0]=1 [0,1]=2 [1,0]=3 [1,1]=4 )
#Looping through the rows and columns
for (( a=0; a<=1; a++ ))
do
    for (( b=0; b<=1; b++ ))
    do
        if (( ${arr[$a,$b]} % 2 == 0 ))
        then
            echo "Even number found at position [$a,$b]: ${arr[$a,$b]}"
        else
            echo "Odd number found at position [$a,$b]: ${arr[$a,$b]}"
        fi
    done
done
EXPLANATION

The for (( a=0; a<=1; a++ )) initiates an outer for loop and defines an iteration variable that loops through 0 and 1, representing the row index. Then the for (( b=0; b<=1; b++ )) initiates an inner loop and defines an iteration variable b that loops through 0, 1 representing the column index. After that if (( ${arr[$a,$b]} % 2 == 0 )) checks if the value of the current array element is even. Then, it prints a message accordingly.

The conditional statement analyzed data with nested loop.Nested for loop has done some data analysis.

6. Using Nested β€œfor” Loop to Match Pattern

Nested for loop allows programmers to search for a specific pattern within a string inside a 2D associative array and comma-separated values. It will iterate through each array element and split each string at the specified Internal Field Separator (IFS). Then, it will search for a specific pattern within each word. Here is a script to split each array element at commas and search for β€˜n’ within each word:

#!/bin/bash
# Defining 2D array
declare -A arr=( [0,0]="red,green" [0,1]="yellow,blue" [1,0]="violate,majenta" [1,1]="orange,purple" )
#Looping through the rows and columns of the array
for (( a=0; a<=1; a++ ))
do
    for (( b=0; b<=1; b++ ))
    do
        #Split the string at commas and loop through the resulting array
        IFS=',' read -ra words <<< "${arr[$a,$b]}"
        for word in "${words[@]}"
        do
            #searching for words having β€œn”
            if [[ $word == *n* ]]
            then
                echo " β€œn” found at the position [$a,$b]: $word"
            fi
        done
    done
done
EXPLANATION

The for (( a=0; a<=1; a++ ) initiates the outer loop that iterates over the values 0, and 1. Then the for (( b=0; b<=1; b++ )) initiates the inner loop that iterates over the values 0, and 1. After that, the IFS=',' read -ra words <<< "${arr[$a,$b]}" defines Internal Field Separator(IFS) as β€œ,” that splits the string at commas and stores the resulting words in word array.

Afterwards, the for word in "${words[@]}" initiates a loop that iterates through each element of the word array. Then, if [[ $word == *n* ]] checks if the current values of the word contain any β€œn”.

The nested for loop searches for n in the array elements.The nested for loop has done a pattern matching.

7. Nested β€œfor” Loop in Bash to Create Chessboard

The chessboard possesses two boxes of alternating colours in eight-by-eight dimensions. The nested for loop in Bash helps programmers to create this type of chessboard easily. Nested for loop allows iteration over each box position, and the American National Standards Institute (ANSI) code serves the purpose of setting two alternating colors.

To create a chessboard copy this bash script:

#!/bin/bash
#Outer for loop
for (( a = 1; a <= 8; a++ ))
do
    #Inner for loop
    for (( b = 1 ; b <= 8; b++ ))
    do
        sum=$(( $a + $b))
        temp=$(( $sum % 2))
        #setting colors of the chessboard using odd and even number logic
        if [ $temp -eq 0 ];
        then
            echo -e -n "\033[47mΒ  "
        else
            echo -e -n "\033[40mΒ  "
        fi
    done
    #printing a new line
    echo " "
done
EXPLANATION

The sum=$(( $a + $b)) inside the inner loop adds the values of a and b and keeps it to sum. Then temp=$(( $sum % 2)) divides the sum by 2 and keeps the remainder to temp. Then, if [ $temp -eq 0 ]; checks whether the temp is zero, it means the sum is even or not. If yes, then, the echo -e -n "\033[47mΒ  " uses ANSI escape codes to print a space character with black background color; otherwise, it prints a space character with white background color.

The nested loop has printed a chessboard on the terminal.The image shows the creation of a chessboard using nested for loop.

Debugging Nested β€œfor” Loops: Common Errors and Solutions

Error in nested loops is very common as it contains many delicate code expressions and variables. This problem is on a bigger scale when working with large datasets. In this section, some traditional errors of nested for loop are listed, along with a few hacks to overcome these:

  1. Infinite Loops: The infinite loop is the situation when a loop never terminates. It happens if the loop condition is not defined accurately or the loop variables are not incremented or decremented properly. To solve this error, make sure that the loop conditions are defined accurately and that the loop variables are incremented or appropriately decremented in each iteration.
  2. Incorrect Loop Order: The incorrect loop order means keeping the loop in the wrong order, resulting in inaccurate or unexpected output. Improper nesting of the inner loop inside the outer loop or inaccurate definition of loop conditions causes this error. To overcome this problem, properly nest your loops and define your loop conditions.
  3. Memory Issue: Large datasets contain a lot of information and data to process, which might cause memory issues that exceed system resource limits. To solve this problem, split the large dataset into smaller modules to reduce memory usage.
  4. Performance Issues: It is one of the common issues when working with large datasets or complex computing tasks. To overcome this issue, find out the bottleneck by profiling, then optimize the performance of your nested loops or incorporate parallel processing.

Advanced Techniques for Nested Loops in Bash Scripts

Nested for loop in Bash scripting enables programmers to automate complex tasks that require a lot of execution time without using the loop. Incorporating advanced techniques would help programmers fine-tune the scripts’ performance and efficiency. Here are some advanced techniques for using nested loops in Bash scripts:

  1. Continue and Break Statement: The continue and the break statements regulate the flow of a script. The continue statement skips the current iteration of the loop and jumps to the next iteration without executing the commands after the continue statement inside the loop. This helps to skip a certain iteration when a certain condition is met.
    On the other hand, the break statement terminates the loop and jumps to the next portion after the loop without executing any command after the break statement. This helps to terminate the loop when a certain condition is met.
  2. Parallel Processing: To accelerate the speed of nested loops, you can use the & operator and the parallel command. These tools will help you to perform the loops in parallel.
  3. Optimizing Loop Structure: Selecting a proper order of loops and efficient algorithms are essential to developing a nested loop. An optimized order can shorten the execution time by reducing the number of iterations and making the script more concise and readable.
  4. Using Functions: Using functions helps create a capsule of a specific part of the script. This segmentizes a long bash script into different modules, making it easier for readers and hassle-free to maintain for developers.

Conclusion

The nested for loop in bash equips users to automate the multilevel task and saves time. The nested loop can be defined by following generalized or one-line syntax, offering versatility. This article will allow beginners and advanced users to learn about nested for loop in Bash and use it whenever necessary.

People Also Ask

What is the purpose of nested for loop?

The purpose of nested for loop is to iterate through multidimensional data. When using a nested for loop, the outer loop initializes the nested loop, and the inner loop does the specified operation on the data iterating through matrix and tabular data.

Can you nest for loops in Bash?

Yes, you can nest for loops in Bash. The nested for loop enables you to do repetitive tasks like printing permutations and combinations of numbers or processing multidimensional data by iterating within multiple levels.

How many loops can be taken in a nested loop?

The number of loops for defining a nested loop is any reasonable number based on your needs. However, system resources and code complexity might influence your practical limit.

What are the two types of nested loops?

The two types of nested loops are the inner loop and the outer loop. The inner loop or the outer loop can be for loop, while loop, or do while loop.

What kind of loop can be nested?

Any kind of loop can be nested with another kind of loop. This practice is very liberal; you can use any kind of loop, whether an inner loop or an outer loop.

Is there any danger in using nested loops?

Here, I have listed some limitations or dangers associated with using nested loops:

  1. Complexity and Readability: Too much nesting might make reading code difficult. Limiting the depth of nesting is a solution to this problem.
  2. Performance: Too much nesting increases the total number of iterations, which might increase the execution time. To overcome this issue, think about the effectiveness before nesting.
  3. Infinite Loops: This happens if the loop conditions or logic is incorrect. Check the loop conditions, logic, and initialization to avoid this issue.

Related Articles


<< Go Back to For Loop in Bash |Β Loops in Bash | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment