Loops
Loops solve one of programming's most common challenges: performing repetitive tasks efficiently. Instead of copying and pasting the same commands dozens or hundreds of times, you can wrap those commands in a loop and let the computer handle the repetition for you. This not only makes your scripts shorter and cleaner but also makes them easier to maintain and modify.
Whether you need to process a list of files, count from 1 to 100, or keep trying something until it succeeds, loops provide the perfect tool for the job.
Quick Reference: Loop Types
| Loop Type | Description | Common Use |
|---|---|---|
while [[ condition ]] |
Repeats while condition is true | Running until a specific condition changes |
until [[ condition ]] |
Repeats while a condition is false | Running until a specific condition is met |
The While Loop
The while loop repeats a block of code as long as a condition is true. It checks the condition before each iteration, and if the condition is true, it executes the loop body. If the condition becomes false, the loop stops and execution continues after the loop.
When to Use While Loops
- When you need to repeat until a condition changes
- When the number of iterations isn't known in advance
- When implementing counters or timers
- When processing data with conditions
- When you need to check conditions during each iteration
Common While Loop Options
| Syntax | What It Does | When to Use It |
|---|---|---|
while [[ condition ]] |
Repeats while condition is true | When looping based on a Boolean condition |
while (( condition )) |
Repeats while numeric condition is true | When using arithmetic expressions in the condition |
Practical Examples
Basic while loop with counter
In this example, we are demonstrating a basic while loop that counts from 1 to 5. We initialize a counter variable to 1, then use a while loop that continues as long as the counter is less than or equal to 5. Inside the loop, we echo the current count and then increment the counter by 1. It's important to increment the counter inside the loop, otherwise the loop would run forever.
#!/bin/bash
count=1
while [[ $count -le 5 ]]; do
echo "Count: $count"
#or you can use $((count++))
count=$((count + 1))
done
echo "Finished the count is ${count}"
While loop with condition checking
In this example, we are demonstrating a while loop that finds even numbers. We ask the user for a number, then loop from 1 to that number. Inside the loop, we use the modulo operator (%) to check if a number is even (when count % 2 equals 0). If it's even, we add it to a string. We use string concatenation with += to build a list of even numbers separated by commas.
#!/bin/bash
echo "Please enter a number"
read num
count=1
number=""
mod=0
while [[ $count -le $num ]]; do
mod=$((count%2))
if [[ $mod -eq 0 ]]; then
number+="${count},"
fi
count=$((count + 1))
done
number="${number:0:-1}"
echo "The even numbers are ${number}"
While loop with modulo operation - including numbers
In this example, we are demonstrating a while loop that finds numbers divisible by a given number. We ask the user for two numbers: a maximum number and a number to divide by. We then loop from 1 to the maximum number, and for each number, we check if it's evenly divisible by the second number using the modulo operator. If the modulo result is 0, the number is evenly divisible, so we add it to our list.
#!/bin/bash
echo "Please enter a number"
read num
echo "Please enter a number to whole number divide on"
read omit
count=1
number=""
mod=0
while [[ $count -le $num ]]; do
mod=$((count%$omit))
if [[ $mod -eq 0 ]]; then
number+="${count},"
fi
count=$((count + 1))
done
#I did the following to omit the last comma
number="${number:0:-1}"
echo "This is the list of numbers less then or equal to $num inwhich every number is evenly divisable by ${omit} ----- ${number}"
While loop with modulo operation - omitting numbers
In this example, we are demonstrating a while loop that finds numbers NOT divisible by a given number. This is similar to the previous example, but we use -ne (not equal) instead of -eq (equal) in the condition. This means we add numbers to our list when the modulo result is NOT 0, which means the number is NOT evenly divisible by the given number.
#!/bin/bash
echo "Please enter a number"
read num
echo "Please enter a number to omit on"
read omit
count=1
number=""
mod=0
while [[ $count -le $num ]]; do
mod=$((count%$omit))
if [[ $mod -ne 0 ]]; then
number+="${count},"
fi
count=$((count + 1))
done
#I did the following to omit the last comma
number="${number:0:-1}"
echo "This is the list of numbers less than or equal to $num with every number NOT evenly divisable by ${omit} ----- ${number}"
While loop processing a file character by character
In this example, we are demonstrating a while loop that processes a file character by character. We first read the entire file into a variable, then use a while loop with an arithmetic expression (( i++ < ${#file} )) to iterate through each character position. Inside the loop, we use expr substr to extract each character, then check if it equals "a". If it does, we echo the position and increment a counter. This demonstrates how to process strings character by character in a loop.
#!/bin/bash
file=$(cat sometext.txt)
i=0
count=0
while (( i++ < ${#file} ))
do
char=$(expr substr "$file" $i 1)
if [[ $char == "a" ]]; then
echo "The position number for a is $i and it is $char"
count=$((count + 1))
fi
#echo $count
done
echo $count
The Until Loop
The until loop is similar to the while loop, but it repeats as long as a condition is false. It continues looping until the condition becomes true. This is useful when the exit condition is more naturally expressed than the continuation condition.
When to Use Until Loops
- When you want to repeat until a condition becomes true
- When the exit condition is more naturally expressed than the continuation condition
- When implementing counters that need to reach a specific value
Common Until Loop Options
| Syntax | What It Does | When to Use It |
|---|---|---|
until [[ condition ]] |
Repeats until condition becomes true | When the exit condition is clearer than the continuation condition |
Practical Examples
Basic until loop with counter
In this example, we are demonstrating a basic until loop that continues until the counter is greater than 10. The until loop works opposite to the while loop - it continues as long as the condition is false. So until [[ $count -gt 10 ]] means "continue looping until count is greater than 10", which is the same as while [[ $count -le 10 ]].
#!/bin/bash
count=1
while [[ $count -le 10 ]]; do
echo "Count: $count"
count=$((count + 1))
done
echo "Finished the count is ${count}"
count=1 #reset the counter for the until loop
until [[ $count -gt 10 ]]; do
echo "Count: $count"
count=$((count + 1))
done
echo "Finished the count is ${count}"
Learning Aids
Tips for Success
- Always increment counters inside loops - A while or until loop without changing the condition variable will run forever
- Initialize variables before loops - Set counter variables like
count,number, andmodto their starting values before the loop begins - Use meaningful variable names - Names like
count,num,mod, andnumberare clearer than single letters - Understand modulo operations - The modulo operator (%) is useful for checking divisibility and finding even/odd numbers
- Use string concatenation with += - When building strings in loops, use
variable+="value"to append to the string - Remove trailing characters when needed - Use
${variable:0:-1}to remove the last character from a string (like removing a trailing comma) - Include comments for complex logic - Explain what the loop is doing, especially for loops with modulo operations or string manipulation
- Choose the right comparison operator - Use
-lefor less than or equal,-gtfor greater than,-eqfor equal, and-nefor not equal
Common Mistakes to Avoid
- Forgetting to increment counters - A while loop without changing the condition variable will run forever
- Using the wrong comparison operator - Remember
-leis less than or equal,-gtis greater than - Forgetting to quote variables - Without quotes, variables with spaces can break your loop conditions
- Infinite loops - Always ensure your loop has a valid exit condition that will eventually be met
- Off-by-one errors - Make sure your loop conditions include or exclude the correct boundary values
- Not initializing variables - Always set counter and accumulator variables to their starting values before the loop
- Missing done keywords - Each do needs a matching done to close the loop block
Best Practices
- Keep loops focused - Each loop should have a single, clear purpose
- Break complex tasks into multiple loops - Use separate loops for separate tasks rather than one complex loop
- Handle edge cases - Test what happens with empty input or unexpected values
- Set default values - Initialize variables before using them in loops
- Use comments to explain complex logic - Especially for loops with modulo operations or string manipulation
- Test with small numbers first - Verify functionality with small input values before testing with large numbers
- Increment counters at the end - Place counter increments at the end of the loop body for clarity