How to Use Nested for Loop in Bash Shell?

In Bash scripting, a nested for loop is an inner loop placed inside another one. 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. It is useful for manipulating multiple items as a two-dimensional output i.e rows and columns. 

This guide shows the complete procedure to make a nested for loop in a Bash Shell.

  • How to Use Nested for Loop in Bash Shell?
    • General Syntax
    • Syntax of One Line Nested for Loop:
  • Print the Range of Numbers
  • Print the set of Strings
  • Print Numbers and Strings
  • Print Specific Pattern
  • Print a Series of Numbers/Strings

How to Use Nested for Loop in Bash Shell?

The working of the nested for loop depends on its simple and generalized syntax to perform the defined task in iteration. The syntax is given below:

General Syntax:

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

The “general” syntax is illustrated here:

  • for” is the main keyword that iterates on the lists of defined items
  •  “list” stores a series of both integer and string values.
  • do” and “done” keywords show the start and end of each “for” loop.

On the other hand, the user can also be used the short one-liner nested for-loop syntax that is stated below:

Syntax of One Line Nested for Loop:

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

The working of both syntaxes is similar and performs the same functionality. It’s a user’s choice whether to choose the general one or “one-liner”.

Example 1: Print the Range of Numbers

The simple and most basic operation is the printing of numeric or string values simultaneously with the help of a nested for loop. It helps in saving the time that is consumed by using multiple print statements one by one for each value.

Let’s see how to work with a Bash script.

Create/Open a bash Script

The “loop1.sh” is an existing bash script taken as an example in the “nano” text editor:

$ nano loop1.sh

Script

#!/bin/bash

for num1 in 1 2 3
do
    for num2 in 10 20 30
do
      echo "The value is "$num1":"$num2
done
done

Script Description:

  • The “#!/bin/bash” is the “Bash Shebang” which will run the current script in the Bash shell.
  • The “num1” variable of “first” for the loop stores a list of “3” numbers.
  • The “num2” variable of the “second” for loop holds the range of “3” numbers also.
  • The “echo” command will print the “$num1” and “$num2” variables values separated by “:(colon)”.
  • The iteration process of the inner loop will continue till the last item of the outer for loop:

Execute the “loop1.sh” script in the command line terminal:

$ ./loop1.sh

The output shows all the iterated numbers of both the inner and outer “for” loops.

Example 2: Print the Set of Strings

The for loop is also useful to iterate the list of strings or characters the same as the numbers. This example provides the practical implementation of the string and characters with the help of generalized “for” loop syntax:

Script

#!/bin/bash

for var1 in a b c d
do
    for var2 in Linux Ubuntu Fedora CentOS
do
      echo $var1":"$var2
done
done

Script Description:

  • The outer for loop will iterate on the string values defined in the “var1” variable.
  • The inner for loop will iterate for the “var2” variable having a list of “4” characters.
  • The “echo” command will display the “$var1:$var2” values in the form of standard output:

Run the “loop2.sh” script for checking the output:

$ ./loop2.sh

The nested for loop has successfully iterated for each string value or character.

Example 3: Print Numbers and Strings

The “for” loop supports each type of value in its list. Here in this example, we will print both string and numeric values via the nested “for” loop:

Script

#!/bin/bash

for num in 1 2 3 4
do
    for var in a b c d
do
      echo $num":"$var
done
done

Script Description:

  • The outer for loop contains a “num” variable having “4” integer values.
  • On the other hand, the inner for loop has a “var” variable holding “4” characters.
  • The “echo” statement will show the iterated values of “$num:$var” variables:

Next, execute the bash “loop3.sh” script:

$ ./loop3.sh

The output contains a list of both inner and for loop iterated values.

Example 4: Print Specific Pattern

The special task performed by the nested for loops is to print a specific pattern. The nested for loop assists the users to display a unique pattern design in the terminal as per requirement. Let’s check how we can do this.

Script

#!/bin/bash
for a in 1 2 3 4 5 6 7 8 9 10
do
    for b in $(seq -10 -$a)
    do
        echo -n  ' '
    done
    for c in $(seq 1 $a)
    do
        echo  -n  "* "
    done
    echo
done

Script Description:

  • The outer for loop stores “a” variable that contains “10” numbers in the list.
  • The first inner for loop contains the “b” variable whose value is enclosed in “command substitution”. 
  • The $() shows “seq(sequence command)” that starts from -10 and each value will decrement by “-$a” variable value at each iteration.
  • The last “echo” will show nothing i.e., whitespaces.
  • The second inner for loop has a “c” variable having a “seq” command starting from “1” and will increment by a “$a” value.
  • The “echo” statement will print the “*(asterisk)” character.

Run the “loop4.sh” script and check the pattern design:

$ ./loop4.sh

The output shows a pattern iterated through the nested for loop.

Example 5: Print Series of Numbers/Strings

Apart from writing each value in the list of nested for loops utilize the brace expansion, i.e., {#…#} for creating a sequence of values.

Let’s understand this concept through the “loop5.sh” bash script using one-liner nested for loop syntax:

Script

#!/bin/bash 
for i in {1..5}; do for j in {1..5}; do echo $i$j; done; done

Script Description:

  • The outer for loop contains a series of numbers from 1 to 5 in the “i” variable.
  • The inner for loop also stores the range of “5” numbers i.e {1..5} in the j variable.
  • The “echo” prints both loop values sequentially via “$i$j”:

Lastly, run the “loop5.sh” script in this way:

$ ./loop5.sh

The output is the same as expected from the generalized syntax of nested for loop.

Conclusion

In Linux, the “nested for” loop is the sequence of more than one for loop to iterate multiple lists of values at once. It contains a list of inner “for” loops that are useful to print the two-dimensional task i.e., rows and columns. It supports two types of basic syntaxes to perform the task i.e., “generalized” and “one line”. 

This guide has provided a deep insight into nested for loops in the bash shell.