Bash for loop

In Bash scripting, loops are an essential control structure that allows you to execute a set of commands repeatedly.
Bash for loop

On this page

In Bash scripting, loops are an essential control structure that allows you to execute a set of commands repeatedly. One of the most commonly used types of loops is the for loop, which iterates over a sequence of values. The Bash for loop provides a flexible and powerful way to automate repetitive tasks, making it an indispensable tool for system administrators, DevOps engineers, and developers working in a Unix-like environment.

In this article, we'll explore the various forms of the for loop in Bash, including the standard syntax and the C-style variant. We'll also delve into the use of the break and continue statements for controlling loop execution, and covering nested loops for more complex iterations. Throughout the article, we'll provide clear code examples and step-by-step explanations to ensure a thorough understanding of the concepts.

Standard Bash for Loop

The standard Bash for loop has the following syntax:

for variable in list
do
  commands
done

Here, variable is a temporary variable that takes on each value from the list in turn, and the commands are executed for each iteration. The list can be a list of values separated by spaces, strings separated by spaces, a range of numbers, or even the output of a command.

Loop Over Number Ranges

One common use case for the for loop is to iterate over a range of numbers. This can be achieved using the seq command, which generates a sequence of numbers:

# Loop from 1 to 5
for i in $(seq 1 5)
do
  echo $i
done

Here's how it works:

  • The loop starts by assigning the first value from the sequence $(seq 1 5) to the  variable i.
  • The echo $i command within the loop body is then executed.
  • The loop then moves to the next value in the sequence, assigns it to the variable, and executes the echo $i command again.
  • This process continues until all values in the sequence have been iterated over.

You can also specify an increment value for the sequence:

# Loop from 1 to 10, incrementing by 2
for i in $(seq 1 2 10)
do
  echo $i
done

Here is another common alternative syntax for specifying a range of numbers:

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

The above syntax is more common in bash scripts. Starting from Bash 4, it’s now possible to specify an increment when using ranges. Here is what it looks like:


# start..end..increment
for i in {1..10..2}
do
  echo "Iteration $i"
done

Loop Over Strings

The for loop can also iterate over a list of strings. Consider the following example:

# Loop over a list of strings
for color in red green blue
do
  echo "The color is $color"
done

In this case, the loop iterates over the specified color strings, displaying each one in the output.

You can also use the for loop to iterate over characters in a string:

mystring="Hello, World!"
for char in $(echo "$mystring" | grep -o .)
do
    echo "$char"
done

In the above example:

  • The string "Hello, World!" is stored in the variable mystring.
  • The grep -o . command matches and prints each character in the string individually.
  • The for loop iterates over each character output by grep, assigning it to the variable char.
  • Within the loop body, the current character is printed using the echo command.

Loop Over Arrays

Bash arrays provide a convenient way to store multiple values. Let's see how to use a for loop to iterate over the elements of an array:

# Define an array
colors=("red" "green" "blue")

# Loop over the array
for color in "${colors[@]}"
do
  echo "The color is $color"
done

Here we defined an array named colors and iterate over each element of the array echoing its value. Note the use of the [@] syntax to expand the array into a list of values.

C-Style Bash for Loop

Bash also supports a C-style for loop, which provides more control over loop variables and conditions. The syntax for the C-style for loop is:

for (( variable assignment; condition; iteration process ))
do
  commands
done

Here, variable assignment is executed once before the loop starts, condition is the condition that is evaluated before each iteration, and iteration process is executed after each iteration.

The following example prints numbers from 1 to 5.

# Loop from 1 to 5
for ((i=1; i<=5; i++))
do
  echo $i
done

There are a couple of things you need to know about this syntax:

  • Variable value assignments can contain spaces.
  • It’s possible to omit the dollar sign for the variable in the condition.
  • The equation for the iteration process doesn’t use the expr command format to increment the value of the value.

Break and Continue Statements

The break and continue statements can be used to control the flow of execution within a for loop, allowing you to skip or terminate iterations based on specific conditions. These statements can be particularly useful when dealing with complex or nested loops, or when you want to implement specific logic within your loop.

Break Statement

The break statement terminates the loop immediately and transfers control to the next statement following the loop. This can be useful in situations where you want to exit the loop early based on a certain condition, such as when you've found the desired value or when a specific condition is met.

# Loop through an array and break when a specific value is found
fruits=("apple" "banana" "orange" "grape" "pear")

for fruit in "${fruits[@]}"
do
  if [ "$fruit" == "orange" ]
  then
    echo "Found orange!"
    break
  fi
  echo "Current fruit: $fruit"
done

In this example, the loop iterates over the fruits array, and when the value "orange" is encountered, the break statement is executed, terminating the loop and printing "Found orange!".

Continue Statement

The continue statement skips the current iteration of the loop and moves to the next iteration. This can be useful when you want to skip certain iterations based on a specific condition, such as when dealing with invalid or unwanted data.

# Loop through a range of numbers and skip multiples of 3

for i in $(seq 1 10)
do
  if [ $((i % 3)) -eq 0 ]
  then
    continue
  fi
  echo $i
done

In this example, the loop iterates over the numbers from 1 to 10, but it skips the multiples of 3 using the continue statement.

Both break and continue statements can be used in combination with conditional statements (if, case, etc.) to implement complex logic within your loops. However, it's important to use them judiciously and avoid excessive use, as this can make your code harder to read and maintain.

Nested For Loops

In Bash, it's possible to have one for loop nested inside another for loop. This construct is known as a nested loop, and it allows you to iterate over multidimensional data structures or perform operations that require nested iterations.

The syntax for a nested for loop is as follows:

for outer_variable in outer_list
do
  for inner_variable in inner_list
  do
    commands
  done
done

Here, the outer loop iterates over theouter_list, and for each iteration of the outer loop, the inner loop iterates over the inner_list. The commands are executed for each combination of the outer and inner loop variables.

Consider the following example:

for i in $(seq 1 2)
do
    for j in $(seq 1 3)
    do
        echo "Outer: $i, Inner: $j"
    done
done

Let’s break down the code:

  • The outer loop iterates over the numbers 1 and 2, assigning each value to the variable i.
  • For each iteration of the outer loop, the inner loop iterates over the numbers 1, 2, and 3, assigning each value to the variable j.
  • Within the inner loop body, the current values of i and j are printed using the echo command.

Conclusion

In this article, we've explored the various forms and capabilities of the for loop in Bash scripting. We covered the standard syntax, C-style syntax, looping over number ranges, strings, and arrays. Additionally, we discussed the use of break and continue statements for controlling loop execution and demonstrated nested loops for more complex iterations.

By understanding and applying the concepts presented in this article, you'll be better equipped to write efficient and robust Bash scripts that can automate a wide range of tasks. Remember, practice is key to mastering the for loop and other Bash scripting constructs, so don't hesitate to experiment and explore further examples and use cases.

Subscribe to sysxplore newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!