Introduction

Hello! In this article, we’ll learn about for loops.

for is a construct for repetitive processing (loops). Used when “processing list elements one by one” or “repeating from 1 to 10”, that kind of thing.

What is a for Loop?

for is a control structure for repeating processing a specified number of times or over a range.

Useful for batch processing multiple files or doing something with sequential numbers. You can easily automate repetitive manual work.

Basic Syntax

List-based Form

1
2
3
for variable in list; do
    # Processing to repeat
done

C-style Form (Numeric Loop)

1
2
3
for ((i=1; i<=10; i++)); do
    # Processing to repeat
done

Usage Examples

Example 1: Basic List Loop

1
2
3
for fruit in apple banana orange; do
    echo "Favorite fruit: $fruit"
done

Output:

1
2
3
Favorite fruit: apple
Favorite fruit: banana
Favorite fruit: orange

Example 2: Numeric Range

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

Output:

1
2
3
4
5
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

{1..5} specifies range from 1 to 5.

Example 3: C-style Loop

1
2
3
for ((i=1; i<=3; i++)); do
    echo "Count: $i"
done

Output:

1
2
3
Count: 1
Count: 2
Count: 3

Some people might be more familiar with this style.

Example 4: File Loop Processing

1
2
3
for file in *.txt; do
    echo "Processing: $file"
done

Output:

1
2
3
Processing: file1.txt
Processing: file2.txt
Processing: notes.txt

Can process all .txt files in current directory.

Example 5: Array Loop

1
2
3
4
5
files=("file1.txt" "file2.txt" "file3.txt")

for file in "${files[@]}"; do
    echo "File: $file"
done

Output:

1
2
3
File: file1.txt
File: file2.txt
File: file3.txt

Can process array elements one by one.

Example 6: Loop Command Output

1
2
3
for user in $(cat users.txt); do
    echo "User: $user"
done

Process file contents line by line.

Example 7: Increment by 2

1
2
3
for i in {0..10..2}; do
    echo "Even: $i"
done

Output:

1
2
3
4
5
6
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10

{start..end..increment} specifies step size.

Tips & Notes

  • Wildcards are convenient: Can batch process with *.txt, *.jpg, etc.

    1
    2
    3
    
    for img in *.jpg; do
        convert "$img" "${img%.jpg}.png"
    done
    
  • Filenames with spaces: Enclose in double quotes

    1
    2
    3
    4
    
    for file in *.txt; do
        cat "$file"  # Correct
        cat $file    # Error if filename has spaces
    done
    
  • No matching files: If no files match *.txt, *.txt itself becomes the list

    1
    2
    3
    4
    
    for file in *.txt; do
        [ -f "$file" ] || continue  # Skip if file doesn't exist
        echo "$file"
    done
    
  • break and continue: Break loop or skip iteration

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    for i in {1..10}; do
        if [ $i -eq 5 ]; then
            break  # Exit loop
        fi
        echo $i
    done
    
    for i in {1..5}; do
        if [ $i -eq 3 ]; then
            continue  # Skip this iteration
        fi
        echo $i
    done
    
  • seq command also available: For older systems where {1..10} doesn’t work

    1
    2
    3
    
    for i in $(seq 1 10); do
        echo $i
    done
    

Practical Usage

Batch File Rename

1
2
3
4
5
6
7
#!/bin/bash

for file in *.jpg; do
    newname="photo_${file}"
    mv "$file" "$newname"
    echo "Renamed: $file$newname"
done

Backup Script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/bin/bash

backup_dir="backup_$(date +%Y%m%d)"
mkdir -p "$backup_dir"

for file in *.conf; do
    cp "$file" "$backup_dir/"
    echo "Backed up: $file"
done

echo "Completed: $backup_dir"

Batch Directory Creation

1
2
3
4
5
6
7
#!/bin/bash

for i in {1..10}; do
    dir="project_$i"
    mkdir -p "$dir"
    echo "Created: $dir"
done

Log File Processing

1
2
3
4
5
6
7
#!/bin/bash

for log in /var/log/*.log; do
    echo "=== $log ==="
    tail -n 5 "$log"
    echo
done

Ping Multiple Servers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash

servers=("192.168.1.1" "192.168.1.2" "192.168.1.3")

for server in "${servers[@]}"; do
    echo -n "$server: "
    if ping -c 1 -W 1 "$server" > /dev/null 2>&1; then
        echo "OK"
    else
        echo "NG"
    fi
done

Batch File Content Conversion

1
2
3
4
5
6
7
#!/bin/bash

for file in *.txt; do
    # Convert lowercase to uppercase
    tr '[:lower:]' '[:upper:]' < "$file" > "${file%.txt}_upper.txt"
    echo "Converted: $file"
done

Summary

In this article, we learned about for loops.

Key Points:

  • Repeat processing with for
  • Can loop over lists, ranges, files, etc.
  • Batch process multiple files with wildcards
  • Enclose variables in double quotes for safety

Super useful for batch file processing or repeating the same work multiple times. Work that would be tedious manually can be finished with a single script.

Keep learning Linux commands!