📖 Scenario: You are organizing a list of your favorite fruits to use in a script that will later process them.
🎯 Goal: Create an indexed array in Bash with specific fruit names, then display the array contents.
📋 What You'll Learn
Create an indexed array named fruits with exact values
Add a variable to hold the number of fruits
Use a loop to print each fruit with its index
Print the total number of fruits at the end
💡 Why This Matters
🌍 Real World
Arrays help organize lists of items like filenames, user inputs, or settings in scripts.
💼 Career
Knowing how to use arrays in Bash is essential for automating tasks and managing data in system administration and DevOps roles.
Progress0 / 4 steps
1
Create the indexed array
Create an indexed array called fruits with these exact values in order: Apple, Banana, Cherry, Date, Elderberry.
Bash Scripting
Hint
Use parentheses () to declare an indexed array in Bash.
2
Add a variable for the number of fruits
Create a variable called count that stores the number of elements in the fruits array.
Bash Scripting
Hint
Use ${#array[@]} to get the length of an array in Bash.
3
Loop through the array and print each fruit
Use a for loop with variable i from 0 to count - 1 to print each fruit with its index in the format: Fruit 0: Apple.
Bash Scripting
Hint
Use a C-style for loop in Bash to iterate over array indices.
4
Print the total number of fruits
Print the total number of fruits using the count variable in the format: Total fruits: 5.
Bash Scripting
Hint
Use echo to print the total count variable.
Practice
(1/5)
1. What is the correct way to declare an indexed array named fruits with values apple, banana, and cherry in Bash?
easy
A. fruits=[apple, banana, cherry]
B. fruits=("apple, banana, cherry")
C. fruits={apple banana cherry}
D. fruits=(apple banana cherry)
Solution
Step 1: Understand Bash array declaration syntax
Bash arrays use parentheses with space-separated values, no commas or braces.
Step 2: Check each option's syntax
fruits=(apple banana cherry) uses parentheses and spaces correctly. Square brackets and braces are incorrect. fruits=("apple, banana, cherry") treats all values as one string.