Controlling Loops with break and continue

Tutorial 4 of 5

Introduction

This tutorial aims to provide a comprehensive understanding of controlling loops using 'break' and 'continue' statements in shell scripting. By the end of this tutorial, you will have learned:

  • The 'break' statement and how it controls the flow of loops.
  • The 'continue' statement and how it controls the flow of loops.
  • Practical usage of 'break' and 'continue' in shell scripting with clear examples.

Prerequisites

Before you start, you should have a basic understanding of shell scripting and how loops work in programming.

Step-by-Step Guide

Break Statement

The 'break' statement in shell scripting is used to terminate the execution of the entire loop, after which the control goes to the statement following the loop.

Here's an example:

for (( i=1; i<=10; i++ ))
do
  if [ $i -gt 5 ]
  then
    break
  fi
  echo $i
done

In this example, the 'break' statement is used to stop the loop as soon as the variable i is greater than 5.

Continue Statement

The 'continue' statement is used to skip the current iteration of the loop and continue with the next iteration.

Here's an example:

for (( i=1; i<=10; i++ ))
do
  if [ $i -eq 5 ]
  then
    continue
  fi
  echo $i
done

In this example, the 'continue' statement is used to skip the current iteration when i is equal to 5.

Code Examples

Let's take a look at some more examples.

Break Statement Example

for (( i=1; i<=10; i++ ))
do
  if [ $i -gt 5 ]
  then
    break
  fi
  echo $i
done

This script will output the numbers from 1 to 4. When i is 5, the 'break' condition is met, and the loop is exited.

Continue Statement Example

for (( i=1; i<=10; i++ ))
do
  if [ $i -eq 5 ]
  then
    continue
  fi
  echo $i
done

This script will output the numbers from 1 to 10, skipping 5. When i is 5, the 'continue' condition is met, and that iteration is skipped.

Summary

This tutorial covered the 'break' and 'continue' statements in shell scripting. 'Break' is used to exit a loop entirely, while 'continue' is used to skip the current iteration and continue with the next one. Understanding these concepts is crucial for controlling the flow of loops in your shell scripts.

Practice Exercises

  1. Write a shell script that prints numbers from 1 to 100, but stops after printing 50.
  2. Write a shell script that prints numbers from 1 to 100, but skips any number that is a multiple of 10.

Solutions

for (( i=1; i<=100; i++ ))
do
  if [ $i -gt 50 ]
  then
    break
  fi
  echo $i
done
for (( i=1; i<=100; i++ ))
do
  if (( $i % 10 == 0 ))
  then
    continue
  fi
  echo $i
done

Continue practicing to enhance your shell scripting skills. Happy scripting!