Shell Scripting / Loops in Shell Scripting

Implementing while Loops for Condition-Based Execution

This tutorial will introduce you to 'while' loops in shell scripting. 'While' loops are used to repeat a set of commands until a certain condition is met.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

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

Tutorial: Implementing while Loops for Condition-Based Execution

1. Introduction

This tutorial aims to guide you on how to implement the while loop in shell scripting. The while loop is a control flow statement that allows the execution of a set of commands repeatedly until a certain condition is met.

What you will learn:

  • Understanding the while loop
  • How to implement the while loop
  • Best practices and tips when using the while loop

Prerequisites:

  • Basic knowledge of shell scripting
  • A shell interface (like bash or sh) to run the scripts

2. Step-by-Step Guide

A while loop in shell scripting follows this basic syntax:

while [ condition ]
do
   command1
   command2
   commandN
done

The while loop tests the condition before executing the commands. If the condition evaluates to true, commands between do and done are executed. This process continues until the condition evaluates to false.

Best practices and tips:

  • Ensure your loop has a terminating condition to prevent infinite loops.
  • Indent your code within the loop for better readability.
  • Always comment your code to make it understandable.

3. Code Examples

Example 1: A simple while loop that counts from 1 to 5.

#!/bin/bash

# Initialize counter variable
counter=1

# While loop
while [ $counter -le 5 ]
do
  echo "Counter: $counter"
  ((counter++)) # Increment counter
done

Expected Output:

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

4. Summary

In this tutorial, you've learned about the while loop in shell scripting, its syntax, and how to use it. You also looked at a simple example that demonstrates the while loop.

The while loop is a powerful tool when used correctly. It allows you to automate repetitive tasks, making your scripts more efficient.

Next Steps:

  • Try using while loops in your scripts
  • Explore for and until loops in shell scripting

Additional Resources:

5. Practice Exercises

Exercise 1: Write a script that prints out all even numbers from 1 to 20.

Solution:

#!/bin/bash

# Initialize counter variable
counter=1

# While loop
while [ $counter -le 20 ]
do
  # Check if the number is even
  if (( $counter % 2 == 0 ))
  then
    echo $counter
  fi
  ((counter++))
done

Exercise 2: Write a script that accepts an integer n as input and prints the first n Fibonacci numbers.

Solution:

#!/bin/bash

# Read input
read -p "Enter a number: " n

# Initialize variables
a=0
b=1 

echo "The Fibonacci sequence is: "

for (( i=0; i<n; i++ ))
do
    echo -n "$a "
    fn=$((a + b))
    a=$b
    b=$fn
done
echo

Remember, practice is the key to mastering any programming language. 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

File Size Checker

Check the size of uploaded files.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

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