Bash For Loop with Examples

Master the art of looping in Bash with our comprehensive guide on Bash For Loops. Learn how to automate repetitive tasks, iterate through data, and enhance your scripting skills effectively.

Updated: 22 Feb, 24 by Susith Nonis 8 Min

List of content you will read in this article:

If you're a Linux user or a system administrator, understanding the power of the bash for loop is crucial for efficiently automating tasks. The bash for loop allows you to iterate through a set of values or perform a series of commands until a specific condition is met. In this article, we'll explore various examples of using the bash for loop to enhance your scripting skills and make your tasks more manageable.

Let's start with a simple one-liner for loop bash examples. Suppose you want to print the numbers from 1 to 5. You can achieve this using the following code:

for i in {1..5}; do echo $i; done

In this example, the for loop iterates through the range of numbers from 1 to 5, and the `echo` command prints each value on a separate line. The output will be:

1

2

3

4

5

Often, you might want to perform operations on specific files with a particular extension in a directory. For instance, let's say you want to delete all the ".txt" files in a directory. You can use the following bash for loop:

for file in *.txt; do rm "$file"; done

This loop will iterate through all files with the ".txt" extension and delete each of them.

You can also use the bash for loop to process a list of strings. Suppose you have a list of fruits and want to print each one:

fruits=("Apple" "Banana" "Orange" "Grapes" "Watermelon")

for fruit in "${fruits[@]}"; do

    echo $fruit

done

The output will be:

Apple

Banana

Orange

Grapes

Watermelon

Arrays are a fundamental data structure in bash scripting. Let's see how we can use the for loop to iterate through an array:

numbers=(10 20 30 40 50)

for num in "${numbers[@]}"; do

    echo $num

done

The above code will print each element of the `numbers` array.

In some cases, you might need to execute a for loop based on a specific condition. For instance, let's print the even numbers from 1 to 10:

for ((i=1; i<=10; i++)); do

    if ((i % 2 == 0)); then

        echo $i

    fi

done

The output will be:

2

4

6

8

10

Using for loop bash with variable allows you to control the loop's behavior dynamically. Here's an example of using a variable to determine the loop's range:

 bash

start=1

end=5

for ((i=start; i<=end; i++)); do

    echo $i

done

By changing the values of `start` and `end`, you can adjust the loop's range.

Let's combine multiple commands within a bash for loop. Suppose we want to create five text files named "file1.txt" to "file5.txt":

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

    touch "file$i.txt"

done

This loop will create five empty text files.

You can use the bash for loop with a variable to process elements in an array:

fruits=("Apple" "Banana" "Orange" "Grapes" "Watermelon")

for i in "${!fruits[@]}"; do

    echo "Index: $i, Fruit: ${fruits[i]}"

done

The output will display each fruit along with its index in the `fruits` array.

The `continue` statement allows you to skip the rest of the commands in the loop for a particular iteration. Let's skip the number 3 in the loop from 1 to 5:

for i in {1..5}; do

    if [ $i -eq 3 ]; then

        continue

    fi

    echo $i

done

The output will be:

1

2

4

5

You can use the bash for loop directly in the command line as well. Let's print the numbers from 1 to 3:

for i in 1 2 3; do echo $i; done

The output will be:

1

2

3

You can use command substitution to generate a list of values for the for loop. Let's print the square of numbers from 1 to 5:

for i in $(seq 1 5); do

    echo $((i * i))

done

The output will be:

1

4

9

16

25

You can combine multiple commands on the same line within the for loop. Let's create and display the content of three files:

for i in {1..3}; do

    touch "file$i.txt" && echo "Hello from file $i" > "file$i.txt"

    cat "file$i.txt"

done

This loop will create three files and print their content.

By default, the for loop uses spaces as the delimiter. However, you can specify a different delimiter. Let's loop through a string separated by hyphens:

data="John-Doe-30-New York"

IFS="-" read -ra details <<< "$data"

for detail in "${details[@]}"; do

    echo $detail

done

The output will be each piece of information separated by the hyphen.

You can use bash for loop with 2 variables to process data in pairs. Let's iterate through two arrays simultaneously:

names=("Alice" "Bob" "Charlie")

scores=(80 90 95)

for i in "${!names[@]}"; do

    echo "Name: ${names[i]}, Score: ${scores[i]}"

done

The output will pair the names with their respective scores.

Similarly, you can use more than two variables in the for loop to process even more complex data structures.

Bash For Loop with If

The bash for loop can be combined with the if statement to perform conditional operations. Let's print "Even" or "Odd" based on the numbers from 1 to 5:

for i in {1..5}; do

    if

 ((i % 2 == 0)); then

        echo "$i is Even"

    else

        echo "$i is Odd"

    fi

done

The output will indicate whether each number is even or odd.

Bash For Loop with If Statement

You can also use the `if` statement with the `continue` keyword to skip specific values. Let's skip the number 3 and print the rest from 1 to 5:

for i in {1..5}; do

    if [ $i -eq 3 ]; then

        continue

    fi

    echo $i

done

The output will be:

1

2

4

5

Sometimes, you might encounter situations where you need to process lines with spaces. Let's iterate through a list of names containing spaces:

names=("John Doe" "Alice Smith" "Bob Johnson")

for name in "${names[@]}"; do

    echo "Hello, $name!"

done

The output will greet each person individually.

Of course, the bash for loop is also useful for handling numerical operations. Let's calculate the sum of numbers from 1 to 5:

sum=0

for i in {1..5}; do

    ((sum += i))

done

echo "Sum: $sum"

The output will be:

Sum: 15

You can use a pipe to pass the output of one command as input to another command within the for loop. Let's find the word count of each file in the current directory:

 bash

for file in *; do

    wc -w "$file"

done

The loop will display the word count of each file in the directory.

The bash for loop is a versatile and indispensable tool for automating tasks and processing data in Linux. By mastering its various applications, you can significantly enhance your scripting capabilities. From handling simple lists to complex data structures, the bash for loop empowers you to streamline your workflows and efficiently manage repetitive tasks. Keep experimenting with the bash for loop examples provided in this article to deepen your understanding of bash scripting and become more proficient in your use of the for loop. You can also learn how to run bash scripts using Python here. Happy scripting!

A Bash for loop is a programming construct that allows you to execute a block of code multiple times. It is used to iterate over a range of values or a list of items.

Susith Nonis

Susith Nonis

I'm fascinated by the IT world and how the 1's and 0's work. While I venture into the world of Technology, I try to share what I know in the simplest way with you. Not a fan of coffee, a travel addict, and a self-accredited 'master chef'.