Recall & Review
beginner
What is an associative array in Bash?
An associative array in Bash is a collection of key-value pairs where keys are strings instead of numbers. It lets you store and access data using named keys.
Click to reveal answer
beginner
How do you declare an associative array in Bash?
Use
declare -A array_name to declare an associative array before using it.Click to reveal answer
beginner
How do you assign a value to a key in an associative array?
Use
array_name[key]=value. For example, colors[apple]=red assigns 'red' to the key 'apple'.Click to reveal answer
beginner
How do you access a value from an associative array?
Use
${array_name[key]}. For example, ${colors[apple]} returns the value for the key 'apple'.Click to reveal answer
intermediate
How can you list all keys in an associative array?
Use
${!array_name[@]} to get all keys. For example, ${!colors[@]} lists all keys in the 'colors' array.Click to reveal answer
Which command declares an associative array named 'fruits' in Bash?
✗ Incorrect
Use
declare -A to declare an associative array. declare -a is for indexed arrays.How do you assign the value 'yellow' to the key 'banana' in an associative array named 'fruits'?
✗ Incorrect
Keys and values with spaces or special characters should be quoted. The correct syntax is
fruits["banana"]="yellow".How do you print the value of the key 'apple' from the associative array 'fruits'?
✗ Incorrect
Use
${array_name[key]} to access values. So echo ${fruits[apple]} prints the value.Which expression lists all keys of an associative array named 'fruits'?
✗ Incorrect
${!fruits[@]} returns all keys. ${fruits[@]} returns all values.What happens if you try to use an associative array without declaring it with
declare -A?✗ Incorrect
Bash throws an error (e.g., 'must use subscript when assigning to an array') because non-numeric keys require
declare -A for associative arrays.Explain how to create and use an associative array in Bash with an example.
Think about how you name the array, add keys and values, and get values back.
You got /4 concepts.
Describe how to list all keys and all values from an associative array in Bash.
Remember the special syntax with exclamation mark for keys.
You got /3 concepts.