Using arrays with loops in bash

In Bash, you can use arrays in conjunction with loops to iterate over the elements of an array and perform actions on each element. Here’s an example that demonstrates how to use arrays with loops in Bash:

#!/bin/bash

fruits=("apple" "banana" "orange" "grape")

# Iterate over the elements using a for loop
echo "Using a for loop:"
for fruit in "${fruits[@]}"; do
    echo "Fruit: $fruit"
done

# Iterate over the elements using a while loop
echo "Using a while loop:"
index=0
while [ $index -lt ${#fruits[@]} ]; do
    echo "Fruit: ${fruits[$index]}"
    ((index++))
done

In this example, we have an array called fruits that contains several fruits. We demonstrate two types of loops: a for loop and a while loop.

In the for loop, we use the syntax for fruit in "${fruits[@]}" to iterate over each element in the fruits array. The fruit variable is assigned to each element, and we can perform actions on it within the loop.

In the while loop, we use an index variable index to keep track of the current index in the array. We use the ${#fruits[@]} syntax to get the length of the fruits array. The loop continues as long as the index is less than the length of the array. Within the loop, we access each element using the syntax ${fruits[$index]}.

When you run this script, it will output:

Using a for loop:
Fruit: apple
Fruit: banana
Fruit: orange
Fruit: grape
Using a while loop:
Fruit: apple
Fruit: banana
Fruit: orange
Fruit: grape

Both the for loop and the while loop iterate over the elements of the fruits array and print each fruit.

Using arrays with loops allows you to process each element in the array sequentially, performing operations or accessing values as needed. This is useful for scenarios where you need to perform batch operations or apply a specific action to each element of an array.

Leave a Comment

Your email address will not be published. Required fields are marked *