0
0
Bash Scriptingscripting~15 mins

Associative arrays (declare -A) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Associative Arrays in Bash
📖 Scenario: You are managing a small store's inventory. You want to keep track of product prices using a simple script.
🎯 Goal: Create a Bash script that uses an associative array to store product names and their prices, then display the price of each product.
📋 What You'll Learn
Use an associative array declared with declare -A
Store exact product-price pairs as given
Use a for loop to iterate over the associative array
Print each product and its price in the format: Product: Price
💡 Why This Matters
🌍 Real World
Associative arrays help store and manage key-value pairs like product prices, user settings, or configuration options in scripts.
💼 Career
Knowing associative arrays is useful for automating tasks, managing data in scripts, and writing efficient shell scripts in system administration or DevOps roles.
Progress0 / 4 steps
1
Create an associative array with products and prices
Create an associative array called products using declare -A. Add these exact entries: apple=100, banana=40, orange=70.
Bash Scripting
Need a hint?

Use declare -A products to create the associative array. Then assign the key-value pairs inside parentheses.

2
Add a variable to count the number of products
Create a variable called count that stores the number of products in the products associative array.
Bash Scripting
Need a hint?

Use ${#products[@]} to get the number of keys in the associative array.

3
Loop through the associative array to print products and prices
Use a for loop with the variable product to iterate over the keys of products. Inside the loop, get the price using ${products[$product]}.
Bash Scripting
Need a hint?

Use "${!products[@]}" to get all keys. Then access each value with ${products[$product]}.

4
Print each product and its price
Inside the for loop, print the product and price in the format: Product: Price. Use echo with the variables product and price.
Bash Scripting
Need a hint?

Use echo "$product: $price" to print each pair.