Introduction
The for
loop is an essential programming functionality that goes through a list of elements. For each of those elements, the for
loop performs a set of commands. The command helps repeat processes until a terminating condition.
Whether you're going through an array of numbers or renaming files, for
loops in Bash scripts provide a convenient way to list items automatically.
This tutorial shows how to use Bash for
loops in scripts.
Prerequisites
- Access to the terminal/command line (CTRL+ALT+T).
- A text editor, such as Nano or Vi/Vim.
- Elementary programming terminology.
Bash Script for Loop
Use the for
loop to iterate through a list of items to perform the instructed commands.
The basic syntax for the for
loop in Bash scripts is:
for <element> in <list>
do
<commands>
done
The element, list, and commands parsed through the loop vary depending on the use case.
Bash For Loop Examples
Below are various examples of the for
loop in Bash scripts. Create a script, add the code, and run the Bash scripts from the terminal to see the results.
Individual Items
Iterate through a series of given elements and print each with the following syntax:
#!/bin/bash
# For loop with individual numbers
for i in 0 1 2 3 4 5
do
echo "Element $i"
done
Run the script to see the output:
. <script name>
The script prints each element from the provided list to the console.
Alternatively, use strings in a space separated list:
#!/bin/bash
# For loop with individual strings
for i in "zero" "one" "two" "three" "four" "five"
do
echo "Element $i"
done
Save the script and run from the terminal to see the result.
The output prints each element to the console and exits the loop.
Range
Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:
#!/bin/bash
# For loop with number range
for i in {0..5}
do
echo "Element $i"
done
The script outputs all elements from the provided range.
The range syntax also works for letters. For example:
#!/bin/bash
# For loop with letter range
for i in {a..f}
do
echo "Element $i"
done
The script outputs letters to the console in ascending order in the provided range.
The range syntax works for elements in descending order if the starting element is greater than the ending.
For example:
#!/bin/bash
# For loop with reverse number range
for i in {5..0}
do
echo "Element $i"
done
The output lists the numbers in reverse order.
The range syntax works whether elements increase or decrease.
Range with Increment
Use the range syntax and add the step value to go through the range in intervals.
For example, use the following code to list even numbers:
#!/bin/bash
# For loop with range increment numbers
for i in {0..10..2}
do
echo "Element $i"
done
The output prints every other digit from the given range.
Alternatively, loop from ten to zero counting down by even numbers:
#!/bin/bash
# For loop with reverse range increment numbers
for i in {10..0..2}
do
echo "Element $i"
done
Execute the script to print every other element from the range in decreasing order.
Exchange increment 2
for any number less than the distance between the range to get values for different intervals.
The seq Command
The seq
command generates a number sequence. Parse the sequence in the Bash script for
loop as a command to generate a list.
For example:
#!/bin/bash
# For loop with seq command
for i in $(seq 0 2 10)
do
echo "Element $i"
done
The output prints each element generated by the seq
command.
The seq
command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster.
C-Style
Bash scripts allow C-style three parameter for
loop control expressions. Add the expression between double parentheses as follows:
#!/bin/bash
# For loop C-style
for (( i=0; i<=5; i++ ))
do
echo "Element $i"
done
The expression consists of:
- The initializer (
i=0
) determines the number where the loop starts counting. - Stop condition (
i<=5
) indicates when the loop exits. - Step (
i++
) increments the value ofi
until the stop condition.
Separate each condition with a semicolon (;
). Adjust the three values as needed for your use case.
The terminal outputs each element, starting with the initializer value.
The value increases by the step amount, up to the stop condition.
Infinite Loops
Infinite for
loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.
To generate an infinite for
loop, add the following code to a Bash script:
#!/bin/bash
# Infinite for loop
for (( ; ; ))
do
echo "CTRL+C to exit"
done
To terminate the script execution, press CTRL+C.
Infinite loops are helpful when a program runs until a particular condition fulfills.
Break
The break statement ends the current loop and helps exit the for
loop early. This behavior allows exiting the loop before meeting a stated condition.
To demonstrate, add the following code to a Bash script:
#!/bin/bash
# Infinite for loop with break
i=0
for (( ; ; ))
do
echo "Iteration: ${i}"
(( i++ ))
if [[ i -gt 10 ]]
then
break;
fi
done
echo "Done!"
The example shows how to exit an infinite for
loop using a break
. The Bash if statement helps check the value for each integer and provides the break
condition. This terminates the script when an integer reaches the value ten.
To exit a nested loop and an outer loop, use break 2
.
Continue
The continue
command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the continue
statement works in a for
loop:
#!/bin/bash
# For loop with continue statement
for i in {1..100}
do
if [[ $i%11 -ne 0 ]]
then
continue
fi
echo $i
done
The code checks numbers between one and one hundred and prints only numbers divisible by eleven.
The conditional if
statement checks for divisibility, while the continue
statement skips any numbers which have a remainder when divided by eleven.
Arrays
Arrays store a list of elements. The for
loop provides a method to go through arrays by element.
For example, define an array and loop through the elements with:
#!/bin/bash
# For loop with array
array=(1 2 3 4 5)
for i in ${array[@]}
do
echo "Element $i"
done
The output prints each element stored in the array from first to last.
The Bash for
loop is the only method to iterate through individual array elements.
Indices
When working with arrays, each element has an index.
List through an array's indices with the following code:
#!/bin/bash
# For loop with array indices
array=(1 2 3 4 5)
for i in ${!array[@]}
do
echo "Array indices $i"
done
Element indexing starts at zero. Therefore, the first element has an index zero.
The output prints numbers from zero to four for an array with five elements.
Nested Loops
To loop through or generate multi-dimensional arrays, use nested for
loops.
As an example, generate decimal values from zero to three using nested loops:
#!/bin/bash
# Nested for loop
for (( i = 0; i <= 2; i++ ))
do
for (( j = 0 ; j <= 9; j++ ))
do
echo -n " $i.$j "
done
echo ""
done
The code does the following:
- Line 1 starts the
for
loop at zero, increments by one, and ends at two, inclusive. - Line 3 starts the nested
for
loop at zero. The value increments by one and ends at nine inclusively. - Line 5 prints the values from the
for
loops. The nested for loops through all numbers three times, once for each outer loop value.
The output prints each number combination to the console and enters a new line when the outer loop finishes one iteration.
Strings
To loop through words in a string, store the string in a variable. Then, parse the variable to a for
loop as a list.
For example:
#!/bin/bash
# For loop with string
strings="I am a string"
for i in ${strings}
do
echo "String $i"
done
The loop iterates through the string, with each word being a separate element.
The output prints individual words from the string to the console.
Files
The for
loop combined with proximity searches helps list or alter files that meet a specific condition.
For example, list all Bash scripts in the current directory with a for
loop:
#!/bin/bash
# For loop with files
for f in *.sh
do
echo $f
done
The script searches through the current directory and lists all files with the .sh extension.
Loop through files or directories to automatically rename or change permissions for multiple elements at once.
Command Substitution
The for
loop accepts command substitution as a list of elements to iterate through.
The next example demonstrates how to write a for
loop with command substitution:
#!/bin/bash
# For loop with command substitution
list=`cat list.txt`
# Alternatively, use list=$(cat list.txt)
for i in $list
do
echo $i
done
The Bash comment offers an alternative syntax for command substitution. The code reads the contents of the list.txt file using the cat
command and saves the information to a variable list
.
Use the command substitution method to rename files from a list of names saved in a text file.
Note: Learn how to use the cat command and for loop to read files line by line in Bash.
Command Line Arguments
Use the for
loop to iterate through command line arguments.
The following example code demonstrates how to read command line arguments in a for
loop:
#!/bin/bash
# For loop expecting command line arguments
for i in $@
do
echo "$i"
done
Provide the command line arguments when you run the Bash script.
For example:
. <script name> foo bar
The $@
substitutes each command line argument into the for
loop.
Conclusion
After following this tutorial, you know how to use the for
loop in Bash scripts to iterate through lists.
Next, learn how to write and use Bash functions.