Introduction
Hello! In this article, we’ll learn about while loops.
while is a construct that repeats processing while a condition is true. Similar to for, but used when the number of iterations isn’t fixed, or when you want to repeat based on conditions.
What is a while Loop?
while is a control structure that keeps repeating processing as long as a specified condition is true.
“Wait until file is found”, “keep going until user enters ‘quit’” - useful when the end isn’t clearly defined.
Basic Syntax
|
|
Usage Examples
Example 1: Counter Loop
|
|
Output:
|
|
Example 2: Infinite Loop
|
|
Since true is always true, it repeats forever. Stop with Ctrl+C.
Example 3: Read File Line by Line
|
|
Process file contents line by line. I use this a lot.
Example 4: User Input Loop
|
|
Example:
|
|
Example 5: Wait for File Creation
|
|
Keeps looping until file is created.
Example 6: Count Down
|
|
Output:
|
|
Can make countdowns like this too.
Tips & Notes
-
Beware infinite loops: Always true condition means it never stops
1 2 3 4# This never stops while true; do echo "Never stops" doneMake sure you can stop with Ctrl+C or have a
breakto exit. -
break and continue: Control the loop
1 2 3 4 5 6 7 8 9 10while true; do read -p "Input: " input if [ "$input" = "exit" ]; then break # Exit loop fi if [ -z "$input" ]; then continue # Skip to next iteration if empty fi echo "Processing: $input" done -
File reading caution: Watch variable scope when using pipes
1 2 3 4 5 6 7 8 9 10 11# Variables don't persist this way cat file.txt | while read line; do count=$((count + 1)) done echo $count # Empty # This is correct while read line; do count=$((count + 1)) done < file.txt echo $count # Has value -
Add sleep for intervals: Avoid continuous execution
1 2 3 4while true; do # Some processing sleep 1 # Wait 1 second done
Practical Usage
Monitoring Script
|
|
Monitor log files continuously.
Wait for Process
|
|
Wait for specific process to end.
Monitor Disk Usage
|
|
Interactive Menu
|
|
Can make simple interactive menus.
Retry Processing
|
|
Retry on failure.
File Processing (Line by Line)
|
|
Summary
In this article, we learned about while loops.
Key Points:
whilerepeats processing while condition is true- Useful when number of iterations isn’t fixed
- Can exit loops with
break - Beware infinite loops (make sure Ctrl+C works)
Use for when iterations are fixed, while when you want to repeat based on conditions. Monitoring scripts, wait processing, lots of uses - good to remember.
Keep learning Linux commands!