Shell Script · Lesson

Shell Scripting · Lesson 9

Loops in Shell Scripting

Add YouTube embed URL in components/shell/ShellLessons.js

What is a Loop?

A loop allows a block of code to run repeatedly until a certain condition is met. It helps automate repetitive tasks and reduce code duplication.

Why Use Loops?

Automation

Perform repetitive tasks automatically.

Efficiency

Reduce code duplication and simplify logic.

Dynamic Execution

Work with changing values and conditions.

Types of Loops in Shell

  • for loop – Iterates over a list or range
  • while loop – Runs while condition is true
  • until loop – Runs until condition becomes true

Basic Loop Examples

1. Basic Loop Concept

A loop repeats a block of code until a condition is met.

terminal — bash
loops
for i in 1 2 3
do
echo "Number: $i"
done

2. While Loop Concept

A while loop keeps running as long as the condition is true.

terminal — bash
loops
count=1
while [ $count -le 3 ]
do
echo "Count is $count"
count=$((count + 1))
done

3. Until Loop Concept

An until loop runs until the condition becomes true.

terminal — bash
loops
count=1
until [ $count -gt 3 ]
do
echo "Count: $count"
count=$((count + 1))
done

Best Practices

Loop Guidelines

  • Avoid infinite loops unless intentionally required.
  • Use meaningful variable names.
  • Keep loop logic simple and readable.
  • Add comments for complex loops.

Practice Task – Loop Basics

  • Print numbers from 1 to 5 using a loop.
  • Create a loop to display your name 3 times.
  • Modify the loop to stop at a condition.

Next lesson: For Loop (Detailed)