Shell Script · While Loop

Shell Scripting · Lesson 11

While Loop

Use while loop for condition based execution. Read files line by line. Monitor services using loops. Practical admin scenarios.

What is a While Loop?

A while loop executes a block of code repeatedly as long as the given condition evaluates to true.

It is commonly used when the number of iterations is not known in advance.

Why Use a While Loop?

Dynamic Conditions

Run until a condition becomes false.

Wait & Monitor

Useful for monitoring logs, processes, or input.

Control Flow

Allows continuous execution with condition checks.

While Loop Syntax

while syntax
syntax
while [ condition ]
do
commands
done

While Loop Examples

1. Basic While Loop

Runs while the condition remains true.

terminal — bash
while-loop
count=1
 
while [ $count -le 5 ]
do
echo "Count: $count"
count=$((count + 1))
done

2. While Loop with User Input

Loop continues until user enters 'exit'.

terminal — bash
while-loop
while true
do
read -p "Enter command (type exit to quit): " cmd
if [ "$cmd" = "exit" ]; then
break
fi
echo "You typed: $cmd"
done

3. Read File Using While Loop

Reading a file line by line using while loop.

terminal — bash
while-loop
while read line
do
echo "Line: $line"
done < file.txt

4. Infinite While Loop

A loop that runs forever until manually stopped.

terminal — bash
while-loop
while true
do
echo "Running..."
sleep 2
done

Best Practices

Loop Best Practices

  • Always update the loop condition to avoid infinite loops.
  • Use sleep to prevent high CPU usage.
  • Validate user input before looping.
  • Break loops intentionally using break.

Practice Task – While Loop

  • Create a loop that prints numbers from 1 to 10.
  • Create a loop that waits until user types "exit".
  • Create a loop that reads a file line by line.

Next lesson: Until Loop