Bash For Loop: A Complete Guide to Iteration in Bash Scripting

Bash for Loop

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

When working with shell scripts, repetitive tasks are quite common, from processing multiple files to automating system tasks. The Bash for loop is one of the most powerful constructs for handling such repetitive tasks efficiently. It allows you to iterate through lists, ranges, or command outputs while executing a block of code for each item without manual intervention. 

So whether you are looping through filenames, user inputs, or even numeric ranges, understanding how to use bash for loops effectively can make the bash scripts more efficient, cleaner, and easier to maintain. 

Basic Syntax of the For Loop in Bash

The basic syntax of a Bash for loop is super simple and intuitive. It defines a variable that would take each value from a list or sequence and execute the loop body for all iterations. 

for variable in list

do

# add comments 

Tech Delivered to Your Inbox!

Get exclusive access to all things tech-savvy, and be the first to receive 

the latest updates directly in your inbox.

done

  • variable: A placeholder that stores the current item in the loop.
  • list: A set of values (words, filenames, numbers, etc.) that the loop cycles through.

For example:

for fruit in apple, banana, cherry

do

    echo “I like $fruit”

done

How Bash For Loop Works

When a Bash for loop starts running, Bash iterates through all the items present in the list and temporarily assigns it to the loop variable. The commands inside the do…done block are executed once for each item. 

After the last item, the loop ends, and the script continues the execution for other commands that follow the loop. 

For example:

for file in *.txt

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

do

    echo “Processing file: $file”

done

Here, the loop iterates through every .txt file in the current directory.

Related Article: Bash Shebang: Learn in 5 Minutes!

Using For Loop with Lists

You can manually define a list of strings, file names, or commands for the loop to process. This is useful to automate small and recurring tasks. 

for name in Alice Bob Charlie

do

    echo “Welcome, $name!”

done

You can also use command substitution to create dynamic lists:

for file in $(ls *.log)

do

    echo “Found log file: $file”

done

Bash For Loop with Ranges and Sequences

When you need to work with numbers, you can utilize ranges or brace expansion. 

for i in {1..5}

do

    echo “Iteration $i”

done

Alternatively, you can use the seq command for more flexibility:

for i in $(seq 1 2 10)

do

    echo “Value: $i”

done

This loop prints numbers from 1 to 10 with a step of 2.

Iterating Over Files and Directories

Bash for loops also allow you to automate file and directory operations. You can glob patterns (*, ?) or commands like find to work through multiple files. 

Example 1: Iterating through files in a directory

for file in /path/to/directory/*

do

    echo “File: $file”

done

Example 2: Iterating through specific file types

for img in *.jpg

do

    echo “Processing image: $img”

done

Example 3: Using find for recursive iteration

for file in $(find /var/log -name “*.log”)

do

    echo “Found log file: $file”

done

This approach is useful for large-scale automation tasks like backups, cleanups, or batch processing.

C-Style For Loop in Bash

Bash also allows you to use a C-style syntax for loops, which is similar to languages like C or Java. This is the best style possible for numeric iterations when you need to control the loop variables explicitly. 

Syntax:

for (( initialization; condition; increment ))

do

    # commands

done

Example:

for (( i=1; i<=5; i++ ))

do

    echo “Count: $i”

done

This form is powerful for mathematical operations or when iterating over arrays using index values.

Nested For Loops

You can place one for loop inside another one to perform multi-level operations, such as comparing combinations of items or processing multi-dimensional data. 

Example:

for i in {1..3}

do

    for j in {A..C}

    do

        echo “Pair: $i$j”

    done

done

Nested loops are common in scripts involving matrix operations, nested directories, or batch jobs.

Using Break and Continue in For Loops

Control the loop flow with break and continue statements:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and proceeds to the next one.

Example: Using break

for i in {1..10}

do

    if [ “$i” -eq 5 ]; then

        echo “Breaking at $i”

        break

    fi

    echo “Iteration $i”

done

Example: Using continue

for i in {1..5}

do

    if [ “$i” -eq 3 ]; then

        echo “Skipping $i”

        continue

    fi

    echo “Iteration $i”

done

These control statements make loops more efficient and help handle special conditions or errors gracefully.

Common Bash For Loop Examples

Here are a few common examples that you could base your use cases on. 

TaskExample Code
Loop through users`for user in $(cat /etc/passwd
Rename multiple filesfor file in *.txt; do mv “$file” “${file%.txt}.bak”; done
Delete temporary filesfor tmp in /tmp/*.tmp; do rm -f “$tmp”; done
Ping multiple hostsfor host in 8.8.8.8 1.1.1.1; do ping -c 1 $host; done
Backup configuration filesfor conf in /etc/*.conf; do cp “$conf” /backup/; done

Best Practices for Writing For Loops in Bash

Efficient and reliable scripting mainly depends on writing clean and maintainable loops. You could follow these best practices when using Bash for loops. 

  1. Always enclose your variables in quotes to prevent issues with spaces or special characters.
    for file in “$@”; do

    echo “Processing: $file”

done

  1. Instead of external tools like seq, use built-in native options for expansion of speed.
    for i in {1..10}; do echo $i; done
  2. Avoid using useless UUOC, use input redirection instead.
    while read -r line; do

    echo “$line”

done < file.txt

  1. Test Scripts with set -e and set -u
    set -euo pipefail
  2. Use meaningful variable names.
    for username in “${users[@]}”; do

    echo “Checking user: $username”

done

  1. To maintain loop efficiency, minimize the use of external command calls. 
  2. Add comments to explain your loops and for future reference. 

Conclusion

The bash for loop is a super useful nesting loop in Bash scripting, enabling automation for recurring tasks. Learning how to use it properly will help keep your loops robust, readable, and performant. 

FAQs

How do you write a simple for loop in Bash?

You can write a basic for loop using this syntax:

for i in 1 2 3; do echo $i done
This loop prints numbers 1, 2, and 3 sequentially.

How do you break or skip iterations in a Bash for loop?

Use the break command to exit the loop early and continue to skip the current iteration and move to the next one.

When should you use a Bash for loop scripting?

Use a for loop when you need to process multiple items or perform repetitive tasks such as file operations, batch processing, or automation within scripts.

Marium Fahim
Hi! I am Marium, and I am a full-time content marketer fueled by an iced coffee. I mainly write about tech, and I absolutely love doing opinion-based pieces. Hit me up at [email protected].
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!