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 | for VARIABLE in LIST |
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 afor
loop that iterates over a list of words:1
2
3
4for word in apple banana cherry
do
echo "The fruit is: $word"
done
Output:
1 | The fruit is: apple |
Example 2: Loop Over a Range of Numbers
You can also loop over a sequence of numbers:
1 | for i in {1..5} |
Output:
1 | Number: 1 |
Example 3: Loop Over Files in a Directory
A common use case is looping over files in a directory:
1 | for file in /path/to/directory/* |
This 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 | for file in /home/john/* |
Output:
1 | Processing /home/john/Desktop |
Example 4: C-Style For Loop
Bash also supports a C-style for
loop, similar to loops in languages like C or Java:
1 | for (( i=1; i<=5; i++ )) |
Output:
1 | Iteration 1 |
Summary
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.