Syntax for a for
Loop in Bash
The for
loop in Bash is a control structure that allows you to iterate over a list of items or a range of numbers. It is particularly useful when you know the number of iterations in advance. Below, we will explore the syntax of the for
loop in detail, along with sample code.
Basic Syntax of the for
Loop
The basic syntax of a for
loop in Bash is as follows:
for variable in list
do
# commands to execute for each item
done
In this syntax:
variable
is the name of the variable that will hold the current item from the list during each iteration.list
is a space-separated list of items or a range of numbers.- The
do
keyword indicates the start of the commands to be executed for each item. - The
done
keyword marks the end of thefor
loop.
Example of a for
Loop
Here’s a simple example of using a for
loop to iterate over a list of fruits:
#!/bin/bash
# Using a for loop to iterate over a list of fruits
for fruit in apple banana cherry
do
echo "I like $fruit"
done
In this example:
- The loop iterates over the list of fruits:
apple
,banana
, andcherry
. - For each fruit, it prints a message indicating that the user likes that fruit.
Using a for
Loop with a Range
You can also use a for
loop to iterate over a range of numbers. The syntax for this is:
for variable in {start..end}
do
# commands to execute for each number
done
Here’s an example that prints numbers from 1 to 5:
#!/bin/bash
# Using a for loop with a range
for i in {1..5}
do
echo "Number $i"
done
In this example:
- The loop iterates over the numbers from 1 to 5.
- For each number, it prints the current number.
Using C-style Syntax in a for
Loop
Bash also supports a C-style syntax for for
loops, which is useful for more complex iterations:
for (( initialization; condition; increment ))
do
# commands to execute
done
Here’s an example using C-style syntax to print numbers from 1 to 5:
#!/bin/bash
# Using C-style for loop
for (( i=1; i<=5; i++ ))
do
echo "Number $i"
done
In this example:
- The loop initializes
i
to 1, checks ifi
is less than or equal to 5, and incrementsi
by 1 in each iteration. - For each number, it prints the current value of
i
.
Conclusion
The for
loop in Bash is a versatile tool for iterating over lists and ranges. It allows for clear and concise code, making it easier to perform repetitive tasks. By understanding the different syntaxes available, you can choose the most appropriate one for your specific use case, enhancing the efficiency and readability of your scripts.