How to Use Bash For Loop with Examples in Linux

Bash For Loop Syntax

As explained earlier, the for loop facilitates the iteration over a range of values and executes a set of Linux commands.

for variable_name in value1 value2 value3  .. n
do
    command1
    command2
    commandn
done

Now, let’s explore some examples of using the bash for loop.

Bash For Loop Example

In its most basic form, the for loop follows this structure. In the given illustration, the variable n iterates over a set of numerical values enclosed in curly braces and prints their values to stdout.

for n in {1 2 3 4 5 6 7};
do
   echo $n
done

Bash For Loop with Ranges

While the previous examples explicitly listed the values to iterate over, it’s impractical for a large range of values. To address this, you can specify a range by indicating the start and stop numbers separated by two periods.

In this case, 1 is the initial value, and 7 is the final value in the range.

#!/bin/bash

for n in {1..7};
do
   echo $n
done

Executing the script will list all values within the specified range, similar to the simple loops.

Moreover, you can include a value at the end of the range to cause the for loop to iterate through the values in incremental steps.

#!/bin/bash

for n in {1..7..2};
do
   echo $n
done

Bash For Loops with Arrays

You can efficiently iterate through values defined in an array using a for loop. In the following example, the for loop iterates through all the values inside the fruits array and prints them to stdout.

#!/bin/bash

fruits=("blueberry" "peach" "mango" "pineapple" "papaya") 

for n in ${fruits[@]}; 
do
    echo $n
done

Leave a Reply

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