Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's Terminal journey — lesson 72 of 82.

The for loop is great when you know exactly what items to iterate through. But what if you want to keep looping until a certain condition changes? That's where the while loop comes in.

A while loop continues running as long as its condition remains true. Here's the basic structure:

#!/bin/bash
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done

This script prints numbers 1 through 5.

The loop checks if count is less than or equal to 5. If true, it runs the body, increments the counter using $((...)) for arithmetic, and checks again.

Once count reaches 6, the condition becomes false and the loop stops.

While loops are perfect when you don't know in advance how many iterations you need. For example, you might keep asking for input until the user types "quit":

#!/bin/bash
input=""
while [ "$input" != "quit" ]; do
    read -p "Enter command (quit to exit): " input
    echo "You entered: $input"
done

Be careful with while loops. If the condition never becomes false, your loop runs forever.

Always make sure something inside the loop eventually changes the condition, like incrementing a counter or updating a variable based on user input.

challenge icon

Challenge

Easy

Create a shell script called counter.sh that uses a while loop to print numbers from 1 to 4.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Create a variable called num with the initial value 1
  3. Use a while loop that continues as long as num is less than or equal to 4
  4. Inside the loop, print the current number in the format: Number: [num]
  5. Increment num by 1 after each iteration using $((num + 1))

Make the script executable and run it. Your output should be:

Number: 1
Number: 2
Number: 3
Number: 4

Hint: Use -le for "less than or equal to" comparison. Remember to increment the counter inside the loop with num=$((num + 1)) to avoid an infinite loop. End your while loop with done.

Cheat sheet

A while loop continues running as long as its condition remains true:

#!/bin/bash
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done

The loop checks the condition before each iteration. Use $((...)) for arithmetic operations to increment counters.

While loops are useful when you don't know in advance how many iterations you need, such as waiting for specific user input:

#!/bin/bash
input=""
while [ "$input" != "quit" ]; do
    read -p "Enter command (quit to exit): " input
    echo "You entered: $input"
done

Always ensure something inside the loop eventually changes the condition to avoid infinite loops.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals