This tutorial aims to provide a comprehensive guide on how to work with nested loops in shell scripting. Nested loops are a fundamental concept in programming, allowing for complex iteration over multi-dimensional data structures.
By the end of this tutorial, you will:
Prerequisites:
- Familiarity with basic shell scripting
- Basic understanding of loop constructs
In shell scripts, a loop is a way to repeat a set of commands until a certain condition is met. A nested loop is a loop within a loop. Understanding nested loops is important for dealing with multi-dimensional data structures like arrays and matrices.
The syntax of a nested loop is:
for outerVar in outerSet
do
for innerVar in innerSet
do
command
done
done
In this structure, the outer loop runs once, and then the inner loop runs completely. The inner loop will run its complete cycle for each iteration of the outer loop.
Let's look at some practical examples:
# Outer loop will run 5 times
for i in {1..5}
do
# Inner loop will run 5 times
for j in {1..5}
do
echo -n "$i$j "
done
echo "" # This will create a new line after each outer loop iteration
done
In this script, the outer loop runs five times, and for each iteration, the inner loop also runs five times. The -n
option in the echo
command prevents a new line after each echo. The output will be a 5x5 matrix.
# Outer loop will iterate over all directories
for dir in */
do
echo "Directory: $dir"
# Inner loop will iterate over all files in the current directory
for file in "$dir"*
do
echo "File: $file"
done
done
This script will first iterate over all directories. For each directory, it will then iterate over all files within that directory, printing the directory name and the filename.
In this tutorial, we've covered nested loops in shell scripting, including their syntax, usage, and practical examples.
Next steps for learning could include exploring other shell scripting concepts, such as functions, conditional statements, and arrays.
For more on shell scripting, check out the Bash Academy.
Solution:
```bash
for i in {1..3}
do
for j in {1..3}
do
echo -n "$i$j "
done
echo ""
done
```
This solution is similar to the first example, but modified to print a 3x3 matrix.
Exercise: Write a script that iterates over all directories in the current directory and prints the number of files in each directory.
Solution:
bash
for dir in */
do
echo "Directory: $dir"
count=0
for file in "$dir"*
do
let count++
done
echo "Number of files: $count"
done
This solution is similar to the second example, but with an added counter for each file in a directory.
Remember, practice is key in mastering any programming concept, so try to solve more problems using nested loops. Happy scripting!