Bash Scripting Loops

ShellShellBeginner
Practice Now

Introduction

In this lab, you will learn how to use loops in Bash scripting. Loops are powerful tools that allow you to repeat a set of instructions multiple times, making your scripts more efficient and flexible. We will cover three types of loops: for, while, and until. Additionally, you will explore the break and continue statements, which provide control over loop execution. This lab is designed for beginners and will guide you through each concept step-by-step.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell/ControlFlowGroup -.-> shell/if_else("`If-Else Statements`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("`Directory Creating`") linux/BasicFileOperationsGroup -.-> linux/ls("`Content Listing`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/ControlFlowGroup -.-> shell/until_loops("`Until Loops`") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_expansion("`Arithmetic Expansion`") subgraph Lab Skills shell/if_else -.-> lab-388816{{"`Bash Scripting Loops`"}} linux/echo -.-> lab-388816{{"`Bash Scripting Loops`"}} linux/cd -.-> lab-388816{{"`Bash Scripting Loops`"}} linux/mkdir -.-> lab-388816{{"`Bash Scripting Loops`"}} linux/ls -.-> lab-388816{{"`Bash Scripting Loops`"}} linux/touch -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/comments -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/variables_decl -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/variables_usage -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/for_loops -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/while_loops -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/until_loops -.-> lab-388816{{"`Bash Scripting Loops`"}} shell/arith_expansion -.-> lab-388816{{"`Bash Scripting Loops`"}} end

Setting Up the Environment

Let's start by setting up our working environment. We'll create a new directory to store all our loop experiments.

Open a terminal in the WebIDE. You should be in the /home/labex/project directory by default. If you're not sure, you can always navigate there using this command:

cd /home/labex/project

Now, let's create a new directory for our loop experiments:

mkdir bash_loops
cd bash_loops

This creates a new directory called bash_loops and changes into it. We'll use this directory for all our loop experiments.

Why are we doing this? Organizing your scripts into directories is a good practice. It keeps your work tidy and makes it easier to find and manage your files.

The for Loop

The for loop is used to iterate over a list of values. It's like saying, "For each item in this list, do something." Let's create a script that demonstrates how to use a for loop.

Create a new file called for_loop.sh in the bash_loops directory:

touch for_loop.sh

Now, open the for_loop.sh file in the WebIDE and add the following content:

#!/bin/bash

## Loop through an array of names
echo "Looping through an array:"
NAMES=("Alice" "Bob" "Charlie" "David")
for name in "${NAMES[@]}"; do
  echo "Hello, $name!"
done

echo ## Print an empty line for readability

## Loop through a range of numbers
echo "Looping through a range of numbers:"
for i in {1..5}; do
  echo "Number: $i"
done

Let's break down what this script does:

  1. The first loop goes through an array of names. For each name in the array, it prints a greeting.
  2. The second loop uses a range {1..5} to count from 1 to 5.

The "${NAMES[@]}" syntax might look strange. The @ means "all elements of the array," and the quotes and curly braces ensure that each element is treated as a separate item, even if it contains spaces.

Save the file and make it executable with this command:

chmod +x for_loop.sh

The chmod +x command makes the file executable, which means you can run it as a program.

Now, run the script:

./for_loop.sh

You should see output like this:

Looping through an array:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
Hello, David!

Looping through a range of numbers:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

This demonstrates how for loops can iterate over both arrays and ranges of numbers.

The while Loop

The while loop executes a block of code as long as a specified condition is true. It's like saying, "While this condition is true, keep doing this."

Create a new file called while_loop.sh:

touch while_loop.sh

Open the while_loop.sh file in the WebIDE and add the following content:

#!/bin/bash

## Simple countdown using a while loop
count=5
echo "Countdown:"
while [ $count -gt 0 ]; do
  echo $count
  count=$((count - 1))
  sleep 1 ## Wait for 1 second
done
echo "Blast off!"

Let's break down this script:

  1. We start with count=5 to set our initial countdown value.
  2. The condition [ $count -gt 0 ] means "while count is greater than 0".
  3. Inside the loop, we print the current count, decrease it by 1, and wait for a second.
  4. This continues until count reaches 0, at which point the loop ends.

The sleep 1 command pauses the script for 1 second, creating a real-time countdown effect.

Save the file and make it executable:

chmod +x while_loop.sh

Now, run the script:

./while_loop.sh

You'll see a countdown from 5 to 1, with a one-second pause between each number:

Countdown:
5
4
3
2
1
Blast off!

This demonstrates how a while loop can repeat an action until a condition is no longer true.

The until Loop

The until loop is similar to the while loop, but with an important difference: it continues executing until a specified condition becomes true. It's like saying, "Keep doing this until this condition is true."

Create a new file called until_loop.sh:

touch until_loop.sh

Open the until_loop.sh file in the WebIDE and add the following content:

#!/bin/bash

## Count up to 5 using an until loop
count=1
echo "Counting up to 5:"
until [ $count -gt 5 ]; do
  echo $count
  count=$((count + 1))
  sleep 1 ## Wait for 1 second
done

Let's break down this script:

  1. We start with count=1 as our initial value.
  2. The condition [ $count -gt 5 ] means "until count is greater than 5".
  3. Inside the loop, we print the current count, increase it by 1, and wait for a second.
  4. This continues until count becomes greater than 5, at which point the loop ends.

Save the file and make it executable:

chmod +x until_loop.sh

Now, run the script:

./until_loop.sh

You'll see the numbers 1 through 5 printed, with a one-second pause between each:

Counting up to 5:
1
2
3
4
5

This demonstrates how an until loop can repeat an action until a condition becomes true.

Using break and continue Statements

The break and continue statements are used to control the flow of loops. break exits a loop early, while continue skips the rest of the current iteration and moves to the next one.

Create a new file called break_continue.sh:

touch break_continue.sh

Open the break_continue.sh file in the WebIDE and add the following content:

#!/bin/bash

## Using break to exit a loop early
echo "Demonstration of break:"
for i in {1..10}; do
  if [ $i -eq 6 ]; then
    echo "Breaking the loop at $i"
    break
  fi
  echo $i
done

echo ## Print an empty line for readability

## Using continue to skip iterations
echo "Demonstration of continue (printing odd numbers):"
for i in {1..10}; do
  if [ $((i % 2)) -eq 0 ]; then
    continue
  fi
  echo $i
done

Let's break down this script:

  1. In the first loop, we use break to exit the loop when i equals 6.
  2. In the second loop, we use continue to skip even numbers. The condition $((i % 2)) -eq 0 checks if a number is even (divisible by 2 with no remainder).

The % operator calculates the remainder after division. So i % 2 will be 0 for even numbers and 1 for odd numbers.

Save the file and make it executable:

chmod +x break_continue.sh

Now, run the script:

./break_continue.sh

You should see output like this:

Demonstration of break:
1
2
3
4
5
Breaking the loop at 6

Demonstration of continue (printing odd numbers):
1
3
5
7
9

This demonstrates how break can exit a loop early, and how continue can skip certain iterations based on a condition.

Summary

In this lab, you've learned about three types of loops in Bash scripting:

  1. for loops, which iterate over a list of items or a range of numbers.
  2. while loops, which continue as long as a condition is true.
  3. until loops, which continue until a condition becomes true.

You've also learned about break and continue statements, which give you more control over your loops.

These loop structures are fundamental to many scripts and will allow you to automate repetitive tasks efficiently. Practice using these loops in your own scripts to become more familiar with their behavior and use cases.

Other Shell Tutorials you may like