For Loop in Bash
A for
loop in Bash is a control structure that allows you to repeat a set of commands for each item in a list, over a range, or based on other criteria. It’s commonly used for tasks like iterating over files in a directory, processing elements in an array, or executing a block of code multiple times.
Basic Syntax
The basic syntax of a for
loop in Bash is as follows:1
2
3
4for VARIABLE in LIST
do
# Commands to be executed
done
VARIABLE
is a placeholder that takes the value of each item inLIST
one by one.LIST
can be a list of values, a range of numbers, or even a command that generates a list.The
do
anddone
keywords define the start and end of the loop block.Example 1: Loop Over a List of Values
Here’s an example of a
for
loop that iterates over a list of words:1
2
3
4for word in apple banana cherry
do
echo "The fruit is: $word"
doneOutput:
1
2
3The fruit is: apple
The fruit is: banana
The fruit is: cherryExample 2: Loop Over a Range of Numbers
You can also loop over a sequence of numbers:
1
2
3
4for i in {1..5}
do
echo "Number: $i"
doneOutput:
1
2
3
4
5Number: 1
Number: 2
Number: 3
Number: 4
Number: 5Example 3: Loop Over Files in a Directory
A common use case is looping over files in a directory:
1
2
3
4for file in /path/to/directory/*
do
echo "Processing $file"
doneThis loop will iterate over each file in the specified directory and execute the commands inside the loop for each file.
For example, read all files from/home/john
directory.1
2
3
4for file in /home/john/*
do
echo "Processing $file"
doneOutput:
1
2
3
4
5
6
7
8
9
10Processing /home/john/Desktop
Processing /home/john/Documents
Processing /home/john/Downloads
Processing /home/john/Music
Processing /home/john/Pictures
Processing /home/john/Public
Processing /home/john/Templates
Processing /home/john/Videos
Processing /home/john/snap
Processing /home/john/tutExample 4: C-Style For Loop
Bash also supports a C-style
for
loop, similar to loops in languages like C or Java:1
2
3
4for (( i=1; i<=5; i++ ))
do
echo "Iteration $i"
doneOutput:
1
2
3
4
5Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5Summary
for
loops are versatile and can be used to iterate over lists, ranges, or output from commands.- They are useful for automating repetitive tasks, processing files, and more.
This should give you a solid understanding of how to use for
loops in Bash scripts.