Comprehensive Guide to Bash For Loop Examples: Practical Examples and Syntax Explained

Er Hana By Er Hana
8 Min Read

The for loop in Bash scripting is a powerful tool used to repeat commands and perform repetitive tasks efficiently. Whether you’re managing files, executing commands multiple times, or processing data, mastering the for loop can significantly simplify your scripts.

In this article, we’ll walk through several examples of for loops, starting with the basics and advancing to more complex applications.

Each example includes easy-to-understand explanations, tables, and links to help you understand Bash for loops thoroughly.

What is a For Loop in Bash?

In Bash, a for loop allows us to iterate over a series of items and perform a command for each one. Syntax for the basic for loop in Bash is:

for variable in list
do
    command1
    command2
    ...
done

The loop will execute each command block for each item in the list, using the variable to represent each item in the sequence.

Basic For Loop Example

Let’s start with a simple example that prints numbers from 1 to 5.

Code:

for i in 1 2 3 4 5
do
    echo "Number: $i"
done

Output:

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

In this example, the loop iterates through the numbers 1 to 5, printing each one with the echo command.

Using Ranges in For Loops

We can use {} to specify ranges, which is often simpler and more readable.

Code:

for i in {1..5}
do
    echo "Count: $i"
done

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

This method is especially useful for long sequences since Bash will automatically fill in all numbers in the specified range.

Step Values in For Loops

Sometimes you may need to skip numbers in a loop, which is done by adding a step value {start..end..step}.

Code:

for i in {0..20..5}
do
    echo "Step Value: $i"
done

Output:

Step Value: 0
Step Value: 5
Step Value: 10
Step Value: 15
Step Value: 20

The for loop increments by 5 instead of 1, making it efficient for specific tasks.

Looping Through Arrays

Bash loops are also ideal for processing arrays. Here’s an example with an array of fruits.

Code:

fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
    echo "Fruit: $fruit"
done

Output:

Fruit: apple
Fruit: banana
Fruit: cherry

This loop uses "${fruits[@]}" to reference all elements in the array, iterating over each fruit name.

Looping Over Files in a Directory

You can use for loops to iterate through files in a directory. This is useful for file manipulation and batch processing.

Code:

for file in /path/to/directory/*
do
    echo "Processing $file"
done

Output:

Processing file1.txt
Processing file2.txt
...

Replace /path/to/directory with the directory path containing the files. The loop will display each file name in that directory.

Using C-Style For Loops in Bash

Bash also supports a C-style for loop structure, which can be handy for complex iterations.

Code:

for ((i=1; i<=5; i++))
do
    echo "Iteration $i"
done

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

In this style, you can control the initialization, condition, and increment, making it more flexible for customized loops.

Combining For Loops with Conditional Statements

You can add conditional statements like if statements inside a for loop for greater control.

Code:

for i in {1..10}
do
    if (( $i % 2 == 0 ))
    then
        echo "$i is even"
    else
        echo "$i is odd"
    fi
done

Output:

1 is odd
2 is even
3 is odd
4 is even
...

In this example, the loop uses the if condition to determine whether each number is odd or even.

Nested For Loops

Nested loops allow for more complex operations, like processing two lists simultaneously.

Code:

for i in {1..3}
do
    for j in {a..c}
    do
        echo "Pair: $i$j"
    done
done

Output:

Pair: 1a
Pair: 1b
Pair: 1c
Pair: 2a
Pair: 2b
Pair: 2c
Pair: 3a
Pair: 3b
Pair: 3c

Here, we loop over both numbers and letters to generate all combinations.

Practical Examples of For Loops

Example 1: Counting Lines in Files

Count the number of lines in each text file in a directory.

Code:

for file in *.txt
do
    lines=$(wc -l < "$file")
    echo "$file has $lines lines"
done

This loop uses wc -l to count the lines in each .txt file in the current directory.

Example 2: File Renaming

Rename all .jpg files in a directory by appending _backup to their names.

Code:

for file in *.jpg
do
    mv "$file" "${file%.jpg}_backup.jpg"
done

This loop processes each .jpg file, appending _backup to the filename.

For Loop Syntax Comparison Table

Loop TypeSyntaxDescription
Basic For Loopfor var in list; do commands; doneExecutes commands for each item in the list
Range-Based Loopfor var in {start..end}; do commands; doneLoops over a numerical range
C-Style For Loopfor ((init; cond; increment)); do commands; doneC-style looping for more complex conditions
Array Loopfor var in "${array[@]}"; do commands; doneLoops over elements in an array
Directory Loopfor file in /path/*; do commands; doneIterates through all files in a directory
Nested For Loopfor i in list1; do for j in list2; do commands; done; doneExecutes loops within loops for complex tasks

Best Practices for Using For Loops

  1. Use Range-Based Loops for Simplicity: When iterating over numbers, {1..N} syntax is usually faster and easier to read.
  2. Optimize for Large Files: For handling numerous files, combining loops with find can improve performance.
  3. Avoid Hard-Coding: Make your loops dynamic by using variables for counts or ranges to improve flexibility.
  4. Include Error Handling: Always add checks to handle errors, especially when working with files to avoid data loss or corruption.

Resources and Further Reading

Conclusion

Bash for loops are incredibly versatile and can be applied to a range of tasks, from processing lists and arrays to handling complex conditional logic. By understanding the syntax and applying these practical examples, you can make your scripts more efficient and adaptable for any command-line automation tasks.

Share This Article
By Er Hana
Here, I'm Masroor, the founder of Grey Knight, is a seasoned programmer, web developer, and technology enthusiast with a degree in Computer Science from Punjab Technical University (PTU). With a passion for demystifying complex tech concepts, I Have dedicated my career to providing reliable and easy-to-follow solutions for troubleshooting web, internet, and technology issues.
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *