In Bash, the for
loop is used to iterate over a list of values or elements. It allows you to perform repetitive tasks for each item in the list. Here’s the basic syntax of a for
loop in Bash:
for variable in list; do
# Code to execute
done
The loop iterates over each item in the list
and assigns it to the variable
. The code block inside the loop is then executed for each iteration.
Here’s an example that demonstrates the usage of a for
loop in Bash:
#!/bin/bash
fruits=("apple" "banana" "orange" "grape")
for fruit in "${fruits[@]}"; do
echo "I like $fruit."
done
In this example, the for
loop iterates over the elements of the fruits
array. For each iteration, the current fruit is assigned to the fruit
variable. The code block inside the loop then executes, which simply prints the message “I like <fruit>”.
When you run this script, it will output:
I like apple.
I like banana.
I like orange.
I like grape.
The loop iterates over each fruit in the array and prints the corresponding message.
You can also use a for
loop to iterate over a sequence of numbers by specifying a range:
#!/bin/bash
for ((i=1; i<=5; i++)); do
echo "Number: $i"
done
In this example, the for
loop iterates over the numbers 1 to 5. The i
variable is incremented by 1 in each iteration, and the code block prints the current number.
When you run this script, it will output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
The loop iterates over the specified range of numbers and prints each number.
The for
loop is a powerful construct in Bash for performing tasks on a set of values or elements. It allows you to automate repetitive operations and process collections of data efficiently.