0
0
Bash Scriptingscripting~15 mins

Iterating over arrays in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating over arrays
📖 Scenario: You are managing a list of fruits in a small fruit shop. You want to write a script that goes through each fruit in your list and shows it on the screen.
🎯 Goal: Build a Bash script that creates an array of fruits, sets up a counter, loops through the array to print each fruit with its number, and finally displays all the fruits one by one.
📋 What You'll Learn
Create an array called fruits with the exact values: Apple, Banana, Cherry, Date, Elderberry
Create a variable called count and set it to 1
Use a for loop with the variable fruit to iterate over the fruits array
Inside the loop, print the current count and fruit, then increase count by 1
Print each fruit on its own line as the final output
💡 Why This Matters
🌍 Real World
Automating tasks like listing items, processing lists of files, or managing simple inventories.
💼 Career
Basic scripting skills like looping over arrays are essential for system administrators, DevOps engineers, and anyone working with automation.
Progress0 / 4 steps
1
Create the fruits array
Create an array called fruits with these exact values: Apple, Banana, Cherry, Date, Elderberry.
Bash Scripting
Need a hint?

Use parentheses () to create an array in Bash.

2
Set up the counter
Create a variable called count and set it to 1.
Bash Scripting
Need a hint?

Just write count=1 to start counting from one.

3
Loop through the fruits array
Use a for loop with the variable fruit to iterate over the fruits array. Inside the loop, print the current count and fruit, then increase count by 1.
Bash Scripting
Need a hint?

Use for fruit in "${fruits[@]}" to loop over all fruits.

4
Print the final output
Run the script to print each fruit with its number on its own line.
Bash Scripting
Need a hint?

Just run the script. The echo inside the loop prints each fruit with its number.