</>
Skip to content
Bash lessons (14/29)

Bash — While Loops

Basic while loop

#!/bin/bash

count=0
while [ $count -lt 5 ]; do
    echo "$count"
    ((count++))
done

Reading file line by line

#!/bin/bash

while IFS= read -r line; do
    echo "$line"
done < file.txt

Reading user input

#!/bin/bash

while true; do
    read -p "Enter command (quit to exit): " cmd
    [ "$cmd" = "quit" ] && break
    echo "You entered: $cmd"
done

Until loop

#!/bin/bash

count=0
until [ $count -ge 5 ]; do
    echo "$count"
    ((count++))
done

break and continue

#!/bin/bash

# break
for i in {1..10}; do
    [ $i -eq 5 ] && break
    echo "$i"
done

# continue
for i in {1..10}; do
    [ $((i % 2)) -eq 0 ] && continue
    echo "$i"
done

Infinite loop

#!/bin/bash

while true; do
    echo "Running..."
    sleep 1
    # Use Ctrl+C to stop
done

Mini Practice

Write Bash code that:

  1. Uses a while loop to read user input
  2. Reads a file line by line
  3. Uses until for a countdown
  4. Uses break and continue

Up Next

In the next lesson, you'll learn about Functions — defining and using functions.

Related Topics

Frequently Asked Questions about While Loops

What is While Loops in Bash?

While Loops is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn While Loops?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn While Loops.

Why is While Loops important in Bash?

While Loops is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.