0
0
Bash Scriptingscripting~15 mins

Accessing array elements in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing array elements
📖 Scenario: You are organizing a small fruit basket. You have a list of fruits and want to pick specific fruits by their position in the list.
🎯 Goal: Learn how to create an array, set a position variable, access an element from the array using that position, and display the chosen fruit.
📋 What You'll Learn
Create an array called fruits with the exact values: apple, banana, cherry, date, elderberry
Create a variable called position and set it to 2
Access the fruit at the index stored in position from the fruits array and store it in a variable called chosen_fruit
Print the value of chosen_fruit
💡 Why This Matters
🌍 Real World
Arrays are useful to store lists of items like filenames, user inputs, or configuration options. Accessing elements by position helps automate tasks like selecting specific files or options.
💼 Career
Knowing how to work with arrays and variables in bash scripting is essential for system administrators, DevOps engineers, and anyone automating tasks on Linux or Unix systems.
Progress0 / 4 steps
1
Create the fruits array
Create an array called fruits with these exact values in order: apple, banana, cherry, date, elderberry
Bash Scripting
Need a hint?

Use parentheses to create an array in bash, with items separated by spaces.

2
Set the position variable
Create a variable called position and set it to 2
Bash Scripting
Need a hint?

Just assign the number 2 to the variable position without spaces around the equals sign.

3
Access the fruit at the position
Access the fruit at the index stored in position from the fruits array and store it in a variable called chosen_fruit
Bash Scripting
Need a hint?

Use ${fruits[$position]} to get the element at index position.

4
Print the chosen fruit
Print the value of the variable chosen_fruit using echo
Bash Scripting
Need a hint?

Use echo "$chosen_fruit" to display the fruit name.