0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bash Loops: A Practical Guide

Posted at

Bash Loops: A Practical Guide

Loops in Bash allow you to automate repetitive tasks. This document covers:
1️⃣ Reading from files vs. direct input
2️⃣ for vs while loops (key differences)
3️⃣ Nested loops (loop inside a loop)


1. Reading Lists: File vs. Direct Input

Method 1: Direct Input (Hardcoded List)

for item in "apple" "banana" "cherry"; do
    echo "Fruit: $item"
done

Output:

Fruit: apple  
Fruit: banana  
Fruit: cherry  

Method 2: Read from a File

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

Assumes fruits.txt contains:

apple  
banana  
cherry  

Key Notes:

  • IFS= prevents whitespace issues.
  • -r avoids interpreting backslashes.

2. for vs while Loops

Feature for Loop while Loop
Use Case Iterate over a known list Run until a condition is false
Syntax for var in list; do ... while [ condition ]; do ...
Termination Ends after list is processed Ends when condition is false
Example for i in {1..3}; do ... while [ $i -le 3 ]; do ...

Example: for Loop (Counting)

for i in {1..3}; do
    echo "Number: $i"
done

Example: while Loop (Condition-Based)

counter=1
while [ $counter -le 3 ]; do
    echo "Count: $counter"
    ((counter++))
done

3. Nested Loops (Loop Inside a Loop)

Example: Multiplication Table (Nested for)

for i in {1..3}; do
    for j in {1..3}; do
        echo "$i x $j = $((i * j))"
    done
done

Output:

1 x 1 = 1  
1 x 2 = 2  
1 x 3 = 3  
2 x 1 = 2  
...  
3 x 3 = 9  

Example: while Inside for

for user in "alice" "bob"; do
    echo "User: $user"
    attempts=1
    while [ $attempts -le 2 ]; do
        echo "  Login attempt #$attempts"
        ((attempts++))
    done
done

Output:

User: alice  
  Login attempt #1  
  Login attempt #2  
User: bob  
  Login attempt #1  
  Login attempt #2  

Cheat Sheet: When to Use Which Loop

Scenario Recommended Loop
Known list (files, numbers, etc.) for
Condition-based (e.g., "retry until success") while
Complex iterations (e.g., grids) Nested loops (for/while)

Final Tips

Avoid infinite while loops → Always update the condition (e.g., ((counter++))).
Use break/continue → Exit early or skip iterations.
Quote variables → Prevents word splitting (e.g., "$item").

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?