Shell Scripting / Loops in Shell Scripting

Nested Looping Techniques in Shell Scripts

In this tutorial, we will delve into nested loops in shell scripting. Nested loops allow for complex iterations and are essential for dealing with multi-dimensional data structure…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers looping constructs in shell scripts, including for, while, and until loops.

Introduction

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:

  • Understand the concept of nested loops
  • Know how to implement nested loops in shell scripting
  • Be able to use nested loops to solve real-world problems

Prerequisites:
- Familiarity with basic shell scripting
- Basic understanding of loop constructs

Step-by-Step Guide

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.

Code Examples

Let's look at some practical examples:

  1. Printing numbers in a matrix format
# 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.

  1. Finding and printing all files in a directory and its subdirectories
# 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.

Summary

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.

Practice Exercises

  1. Exercise: Write a script that prints a 3x3 matrix with each cell containing its row and column number.

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.

  1. 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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help