Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Automating Repetitive Tasks with Loops

Recommended resources

Hello! Welcome back to your Bash scripting journey.

In the last lesson, you learned how to give your scripts decision-making abilities using if, elif, and else. This is crucial for creating scripts that can react to different situations. Now, we're going to add another fundamental building block: repetition.

Automating repetitive tasks is at the heart of effective scripting. Whether it's processing hundreds of log files, scanning a range of IP addresses, or waiting for a specific condition to be met, you need a way to perform an action over and over. This is where loops come in.

In this lesson, you will master the two primary loop structures in Bash, which are essential for any aspiring hacker or sysadmin. By the end, you'll be able to use for and while loops to automate repetitive tasks in your scripts, significantly boosting their power and efficiency.

1. The while Loop: Repeating Based on a Condition

A while loop is like an if statement that repeats. It will execute a block of code over and over as long as a specified condition remains true. This is perfect for situations where you don't know in advance how many times you need to loop, such as waiting for a file to appear or for a network service to become available.

The basic syntax is:

while [ condition ]; do



  # commands to execute
done

The logic is straightforward: the script checks the condition. If it's true, it runs the commands in the do...done block and then goes back to check the condition again. This cycle continues until the condition becomes false.

While Loop Flowchart
This flowchart shows the execution path of a `while` loop. The script repeatedly checks a condition and executes the loop body if it's true, only ending when the condition becomes false.

Let's see this in action with a basic counter.

How To Write Bash Scripts In Linux - Complete Guide (Part 7 - While Loops)

The video 'How To Write Bash Scripts In Linux - Complete Guide (Part 7 - While Loops)' from Learn Linux TV provides an excellent walkthrough of creating a basic while loop.

Please watch from 01:26 to 05:23. The presenter clearly explains how to set up a variable, define the loop condition, execute commands, and importantly, how to increment the variable to eventually terminate the loop.

Hands-On 1: Your First while Loop

Now it's your turn. Create a script named counter.sh that counts down from 10 to 1, printing each number, and then prints "Liftoff!".

Hint: You'll need a variable that starts at 10. The condition will check if the variable is greater than 0 (-gt), and inside the loop, you'll need to decrease the variable's value by 1. You can use let counter-=1 or ((counter--)) for this.

Once you have a working script, let's look at a more practical example that's highly relevant to system administration and security monitoring.

How To Write Bash Scripts In Linux - Complete Guide (Part 7 - While Loops)

The same video also demonstrates a more practical use case: a script that monitors for a file's existence. This is a common pattern for creating watchdog scripts or waiting for a process to create a lock file.

Watch from 05:23 to 12:43. Pay attention to how the -f test operator is used in the condition. The presenter also shows how to refine the script by adding a sleep command, which is critical for preventing the loop from consuming 100% of your CPU.


2. The for Loop: Repeating Over a List

While while loops are great for conditional repetition, for loops are designed to iterate over a predefined list of items. For each item in the list, the loop assigns the item to a variable and executes a block of code. This is your go-to tool for tasks like processing a batch of files, users, or IP addresses.

The basic syntax is:

for variable_name in item1 item2 item3; do



  # commands using $variable_name
done

The list can be anything: numbers, strings, filenames, or the output of another command.

How To Write Bash Scripts In Linux - Complete Guide (Part 9 - For Loops)

To understand the fundamental syntax and power of for loops, watch this video from Learn Linux TV.

Watch from 00:37 to 05:57. This segment covers the core concept, the basic syntax, and a very useful shorthand for generating number ranges like {1..10}, which saves you from typing out a long list manually.

Practical Application: Automating File Processing

One of the most powerful uses of for loops is processing files using wildcards. Imagine you need to compress every log file in a directory. A for loop makes this trivial.

How To Write Bash Scripts In Linux - Complete Guide (Part 9 - For Loops)

Let's continue with the same video to see a real-world example of a for loop that automates archiving log files.

Watch from 05:57 to 11:13. The presenter builds a script that finds all files ending in .log in a directory and uses tar to compress each one. This is a perfect demonstration of automating a repetitive sysadmin task.

Hands-On 2: A Simple IP Sweeper

Now for an exercise directly related to your goals. Let's build a basic IP sweeper that pings a range of addresses to see which hosts are online. This is a foundational step in network reconnaissance.

  1. Create a script named ip_sweep.sh.
  2. The script should take the first three octets of a network as a command-line argument (e.g., 192.168.1).
  3. Use a for loop to iterate through the numbers 1 to 254 for the last octet.
  4. Inside the loop, use ping to send a single packet to the constructed IP address.

Here is a starting point for your ip_sweep.sh script:




#!/usr/bin/env bash




# Check if an argument was provided
if [ -z "$1" ]; then
  echo "[-] Usage: $0 <network_prefix>"
  echo "[-] Example: $0 192.168.1"
  exit 1
fi

PREFIX=$1

for i in {1..254}; do



  # The -c 1 flag tells ping to send only one packet.
  # The -W 1 flag sets a timeout of 1 second.
  # We redirect the output to /dev/null because we only care about the exit code.
  ping -c 1 -W 1 "$PREFIX.$i" &> /dev/null && echo "[+] Host $PREFIX.$i is up."
done

echo "[*] IP sweep complete."
  • The && operator is a logical AND. The echo command will only run if the ping command succeeds (i.e., returns an exit code of 0).
  • &> /dev/null redirects both standard output and standard error to /dev/null, effectively silencing the ping command's output.

Make the script executable and run it on your local network (e.g., ./ip_sweep.sh 192.168.1). You've just automated a basic enumeration task!


3. Controlling Loop Behavior: break and continue

Sometimes you need to alter the flow of a loop. Bash provides two commands for this:

  • break: Immediately terminates the loop and continues execution after the done statement.
  • continue: Skips the rest of the commands for the current iteration and starts the next iteration of the loop.

These are useful for handling errors or special cases within your loop.

Controlling Loops: Break and Continue

The article 'Loops - Bash Scripting Tutorial' from ryanstutorials.net has a concise section on these control statements.

Read the section titled 'Controlling Loops: Break and Continue'. The examples for copying files demonstrate a clear, practical use for both break (e.g., stop if disk is full) and continue (e.g., skip a file you can't read).

Hands-On 3: Refining the IP Sweeper

Let's modify your ip_sweep.sh script. Imagine you are scanning a network but want to skip a specific "friendly" host (e.g., the gateway or your own machine). You can use continue to do this.

Update your ip_sweep.sh script to add a check inside the for loop. If the IP address matches a predefined "skip" IP, it should print a message and use continue to move to the next IP without pinging.




#!/usr/bin/env bash

if [ -z "$1" ]; then
  echo "[-] Usage: $0 <network_prefix>"
  echo "[-] Example: $0 192.168.1"
  exit 1
fi

PREFIX=$1
SKIP_IP="$PREFIX.1" # Let's say we want to skip the gateway

for i in {1..254}; do
  TARGET_IP="$PREFIX.$i"
  
  if [ "$TARGET_IP" == "$SKIP_IP" ]; then
    echo "[*] Skipping gateway: $SKIP_IP"
    continue
  fi

  ping -c 1 -W 1 "$TARGET_IP" &> /dev/null && echo "[+] Host $TARGET_IP is up."
done

echo "[*] IP sweep complete."

This simple addition makes your script more intelligent by allowing it to handle exceptional cases within the loop.


Summary and Reference

You've now learned the two main looping constructs and how to control them. To help you remember the syntax for different types of loops, here is a handy cheat sheet.

BASH SCRIPTING LOOPS BASICS
This cheat sheet provides a quick visual reference for the syntax of `for` loops (including C-style and ranges), `while` loops, `until` loops, and the `break` and `continue` control statements.

Conclusion

Mastering loops moves you from writing simple command sequences to building powerful automation tools. You can now write scripts that perform repetitive tasks, a skill that is absolutely essential for both system administration and ethical hacking.

Key Takeaways:

  • while loops are condition-based. They run as long as a condition is true and are ideal for when the number of iterations is unknown.
  • for loops are list-based. They iterate over a finite set of items and are perfect for processing files, users, or a range of numbers.
  • The {start..end} syntax is a highly efficient way to create number ranges for for loops.
  • break exits a loop entirely.
  • continue skips the current iteration and moves to the next one.

Next Lesson Preview:
You now understand variables, conditionals, and loops—the three pillars of procedural programming. In the next lesson, "Read and interpret a short Bash script to determine its function," we will put all these pieces together. You'll be challenged to analyze existing scripts, figure out what they do, and identify how they work. This is a critical skill for understanding tools you may find online or encounter during a penetration test.