Bash 101: How to use for loops
Loops are one of the core building blocks in Bash scripting. They let you run a set of commands repeatedly, which is useful for anything from processing files in a directory to automating system tasks. Among the different types of loops, the for loop is one of the most commonly used. It lets you iterate over a sequence of values, such as numbers, strings, or items in an array.
In this guide, you’ll learn how Bash for loops work. We'll go over the standard syntax, the C-style variant, and how to use break and continue to control loop execution. You’ll also see how nested loops work, with plenty of examples along the way to show how you can use them in real scripts.
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 variablei.The
echo $icommand 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 $icommand 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
doneHere is another common alternative syntax for specifying a range of numbers:
for i in {1..5}
do
echo "Iteration $i"
doneThe 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"
doneLoop 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"
doneIn 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"
doneIn 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
echocommand.
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"
doneHere 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
doneHere, 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
doneThere 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"
doneIn 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
doneIn 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
doneHere, 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
doneLet’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
iandjare printed using theechocommand.
Thanks for reading!
If you enjoyed this content, don't forget to leave a like ❤️ and subscribe to get more posts like this every week.

