Introduction
One of the most fundamental ideas in programming languages is the loop. When you want to run a string of commands multiple times until a certain condition is met, loops come in handy.
Loops are useful for automating repeated operations in scripting languages like Bash.
In Bash scripting, there are three basic loop constructs: for
loop, while
loop, and until
loop.
We'll go through the fundamentals of for
loops in Bash in this tutorial. We will also address a few FAQs on Bash for Loop.
The Standard Bash for Loop
The for
loop iterates across a list of items, carrying out the commands specified.
The Bash for
loop is written as follows:
for item in [LIST]
do
[COMMANDS]
done
The list could be a sequence of strings separated by spaces, a range of integers, the output of a command, an array, or something else entirely.
Loop over strings
The loop will go over each item in the list of strings in the example below, with the variable element set to the current item:
for element in Hydrogen Helium Lithium Beryllium
do
echo "Element: $element"
done
The following is the output of the loop:
Output
Element: Hydrogen
Element: Helium
Element: Lithium
Element: Beryllium
Loop over a number range
By specifying a start and endpoint for the range, you can describe a range of numbers or characters using the sequence expression. The following is an example of a sequence expression:
{START..END}
An example loop that iterates through all numbers from 0 to 3 is as follows:
for i in {0..3}
do
echo "Number: $i"
done
Output
Number: 0
Number: 1
Number: 2
Number: 3
When using ranges, you can now specify an increment starting with Bash 4. The expression is written as follows:
{START..END..INCREMENT}
Here's an example of how to increment by 5:
for i in {0..20..5}
do
echo "Number: $i"
done
Output
Number: 0
Number: 5
Number: 10
Number: 15
Number: 20
Loop over array elements
The for
loop can also be used to iterate over an array of elements.
In the example below, we're creating an array called BOOKS
and iterating through its elements.
BOOKS=('In Search of Lost Time' 'Don Quixote' 'Ulysses' 'The Great Gatsby')
for book in "${BOOKS[@]}"; do
echo "Book: $book"
done
Output
Book: In Search of Lost Time
Book: Don Quixote
Book: Ulysses
Book: The Great Gatsby
The C-style Bash for loop
The C-style for
loop has the following syntax:
for ((INITIALIZATION; TEST; STEP))
do
[COMMANDS]
done
When the loop begins, the INITIALIZATION
portion is only run once. The TEST
section is then assessed. The loop is terminated if it is false. If the TEST
is true, the for
loop's body commands are executed, and the STEP
portion is modified.
The loop in the following example code starts with i = 0
and checks if i ≤ 10
before each iteration. If true, the loop prints the current value of i
and [increments the variable] i
by 1 (i++
), else it ends.
for ((i = 0 ; i <= 1000 ; i++)); do
echo "Counter: $i"
done
The loop will iterate, 1001 times, resulting in the following output:
Output
Counter: 0
Counter: 1
Counter: 2
...
Counter: 998
Counter: 999
Counter: 1000
break
and continue
Statements
The for loop can be controlled using the break
and continue
statements.
break
Statement
The break
statement ends the current loop and transfers control to the statement that comes after it. When a given condition is met, it is frequently used to end the loop.
The if
statement is used in the following example to stop the loop from running once the current iterated item equals 'Lithium.'
for element in Hydrogen Helium Lithium Beryllium; do
if [[ "$element" == 'Lithium' ]]; then
break
fi
echo "Element: $element"
done
echo 'All Done!'
Output
Element: Hydrogen
Element: Helium
All Done!
continue
Statement
The continue
command ends the current loop iteration and moves program control to the next loop iteration.
We're iterating through a set of numbers in the following example. The continue
statement will cause execution to return to the beginning of the loop and continue with the next iteration when the current iterated item equals '2':
for i in {1..5}; do
if [[ "$i" == '2' ]]; then
continue
fi
echo "Number: $i"
done
Output
Number: 1
Number: 3
Number: 4
Number: 5
Bash for
Loop Examples
Rename files with spaces in the filename
By replacing space with an underscore, the following example shows how to rename all files in the current directory that have a space in their names:
for file in *\ *; do
mv "$file" "${file// /_}"
done
Let's take a look at the code one line at a time:
- The first line sets up a
for
loop that loops over a list of all files with a space in their name. The list is created by the expression*\ *
. - The second line replaces the space in each item of the list with an underscore (
_
) and copies the file to a new location. The portion${file// /_}
replaces a pattern within a parameter with a string using shell parameter expansion. - The word
done
denotes the end of a loop segment.
Changing file extension
The following example explains how to use the Bash for
loop to rename all files in the current directory that finish in .jpeg to.jpg by replacing the file extension.
for file in *.jpeg; do
mv -- "$file" "${file%.jpeg}.jpg"
done
Let's take a look at the code one line at a time:
- The first line starts a
for
loop that iterates over a list of all files that end in '.jpeg.' - The second line replaces '.jpeg' with '.jpg' for each item on the list and moves the file to a new location.
${file%.jpeg}
removes the '.jpeg' element of the filename using shell parameter expansion. done
means that the loop segment has ended.
FAQs on Bash for Loop
Can I use a variable in the for
loop?
Yes, you can use a variable in the for
loop. The loop variable takes each value from the specified set, allowing you to perform actions based on that value within the loop.
How can I iterate over a range of numbers in a for
loop?
To iterate over a range of numbers in a for
loop, you can use the {start..end}
syntax. For example: for i in {1..5}; do echo $i; done
will iterate from 1 to 5.
Can I use an array in a for
loop?
Yes, you can use an array in a for
loop. You can iterate over each element of the array by using the ${array[@]}
syntax. For example: myArray=("apple" "banana" "cherry"); for fruit in "${myArray[@]}"; do echo $fruit; done
.
How can I iterate over the contents of a directory in a for
loop?
You can iterate over the contents of a directory in a for
loop by using the *
wildcard to match all files and directories. For example: for file in *; do echo $file; done
.
Can I use nested for
loops in Bash?
Yes, you can use nested for
loops in Bash to perform multiple levels of iteration. This allows you to work with 2D arrays, iterate over combinations of values, or perform complex iterations.
Can I modify the loop variable within a for
loop?
Yes, you can modify the loop variable within a for
loop. However, keep in mind that modifying the loop variable may not have the expected effect, especially if it affects the loop's behavior or termination condition.
How do I exit or terminate a for
loop prematurely?
To exit or terminate a for
loop prematurely, you can use the break
statement. When encountered, the break
statement transfers control to the first line after the loop.
Conclusion
The Bash for
loop is used to run a series of commands over and over again for a predetermined number of times.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.