Chapter 57: Bash Loops
Bash Loops
Loops are one of the superpowers of scripting. Without loops, you have to repeat the same command 10 times by hand:
|
0 1 2 3 4 5 6 7 8 9 |
echo "Hello 1" echo "Hello 2" echo "Hello 3" # ... 97 more times 😴 |
With loops, you write the command once and tell Bash:
“Please repeat this 100 times — or until something happens — or while this is true”
There are three main types of loops in Bash — we’ll learn all three today, step-by-step, with lots of real examples you can type right now.
1. The for loop (most common & easiest)
Use for when you know how many times you want to repeat — or when you want to go through a list of items.
Basic structure:
|
0 1 2 3 4 5 6 7 8 9 |
for variable in list_of_items do # commands using $variable done |
Example 1: Simple count from 1 to 5
|
0 1 2 3 4 5 6 7 8 9 |
for i in 1 2 3 4 5 do echo "Number: $i" done |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 |
Example 2: Better way — use {start..end}
|
0 1 2 3 4 5 6 7 8 9 |
for i in {1..10} do echo "Counting: $i" done |
Example 3: Loop over files (very common!)
|
0 1 2 3 4 5 6 7 8 9 10 |
for file in *.txt do echo "Found text file: $file" # You can cp, mv, cat, grep inside here done |
Example 4: Loop over array
|
0 1 2 3 4 5 6 7 8 9 10 11 |
cities=("Hyderabad" "Delhi" "Mumbai" "Bangalore" "Chennai") for city in "{cities[@]}" do echo "I want to visit $city someday!" done |
Important: Always quote “${array[@]}” — it keeps spaces inside elements safe.
Example 5: C-style for loop (classic programming style)
|
0 1 2 3 4 5 6 7 8 9 |
for (( i=1; i<=10; i++ )) do echo "i = $i" done |
This is very useful when you need a counter with step:
|
0 1 2 3 4 5 6 7 8 9 |
for (( i=0; i<=20; i+=5 )) do echo "Step of 5: $i" done |
2. The while loop (repeat while condition is true)
Use while when you want to keep going until something changes (you don’t know exactly how many times).
Structure:
|
0 1 2 3 4 5 6 7 8 9 |
while [ condition ] do # commands done |
Example 1: Countdown
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
count=5 while [ $count -gt 0 ] do echo "Countdown: $count" ((count--)) done echo "Blast off! 🚀" |
Example 2: Ask user until correct answer
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
answer="" while [[ "$answer" != "yes" ]] do echo "Do you love Bash? (yes/no)" read answer if [[ "$answer" == "no" ]]; then echo "Arre yaar... let me convince you 😄" fi done echo "Yay! Welcome to the Bash fan club!" |
Example 3: Read file line by line (classic)
|
0 1 2 3 4 5 6 7 8 9 |
while IFS= read -r line do echo "Line: $line" done < names.txt |
(IFS= prevents trimming spaces, -r prevents backslash interpretation)
3. The until loop (opposite of while)
Repeat until condition becomes true (rarely used, but good to know).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
count=1 until [ $count -gt 5 ] do echo "Count is $count (still less than or equal 5)" ((count++)) done |
Almost same as while — just reversed logic.
4. Loop Control – break & continue
- break → jump out of the loop immediately
- continue → skip rest of this iteration, go to next one
Example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
for i in {1..10} do if [ $i -eq 5 ]; then echo "Skipping 5..." continue fi if [ $i -eq 8 ]; then echo "Found 8 — stopping loop!" break fi echo "Processing $i" done |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
Processing 1 Processing 2 Processing 3 Processing 4 Skipping 5... Processing 6 Processing 7 Found 8 — stopping loop! |
5. Real-Life Script Using Loops (Type This Now!)
Create backup_files.sh:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/bin/bash echo "Starting backup of important files..." # Array of folders to backup folders=("Documents" "Photos" "Downloads/projects" ".config") for folder in "${folders[@]}" do if [[ -d "$HOME/$folder" ]]; then backup_name="${folder##*/}_$(date +%Y-%m-%d).tar.gz" echo "Backing up ~/$folder → $backup_name" tar -czf "$backup_name" -C "$HOME" "$folder" else echo "Warning: $folder not found — skipping" fi done echo "All backups finished! 🎉 Check your current folder." |
Run:
|
0 1 2 3 4 5 6 7 |
chmod +x backup_files.sh ./backup_files.sh |
Summary Table – Bash Loops Cheat Sheet
| Loop Type | Best When | Syntax Example | Typical Use Case |
|---|---|---|---|
| for | Known number of times / list of items | for i in {1..10}; do … done | Process files, numbers, array items |
| C-style for | Counter with step | for ((i=0; i<10; i++)); do … done | Classic counter, step 2/5/etc |
| while | Repeat until condition false | while [ $count -gt 0 ]; do … done | Countdown, read file line-by-line, wait for event |
| until | Repeat until condition true | until [ $count -gt 5 ]; do … done | Rare — opposite of while |
| break | Exit loop early | if [ condition ]; then break; fi | Stop when found something |
| continue | Skip this iteration | if [ condition ]; then continue; fi | Skip unwanted items |
Got it, boss? Loops are how your script becomes tireless — it can repeat boring work 1 time or 1,000 times without complaining.
Any part confusing? Want next:
- “Teacher, explain nested loops (loop inside loop)”
- “How to loop over command output (find, ls, etc.)”
- “while read line – read files properly”
- “Infinite loops & how to stop them”
- “select loop (simple menu)”
Just say — teacher is ready in Hyderabad! Keep writing small loops every day — even 3–4 lines — soon repeating tasks will feel effortless! 🐧🔄🔁 😄
