0
0
Bash Scriptingscripting~5 mins

Associative arrays (declare -A) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Adeclare -a fruits
Bdeclare fruits
Carray fruits
Ddeclare -A fruits
How do you assign the value 'yellow' to the key 'banana' in an associative array named 'fruits'?
Afruits[banana]=yellow
Bfruits["banana"]="yellow"
Cfruits('banana')=yellow
Dfruits{banana}=yellow
How do you print the value of the key 'apple' from the associative array 'fruits'?
Aecho ${fruits[apple]}
Becho fruits[apple]
Cecho ${fruits.apple}
Decho fruits(apple)
Which expression lists all keys of an associative array named 'fruits'?
A${!fruits[@]}
B${fruits[@]}
C${fruits[*]}
D${#fruits[@]}
What happens if you try to use an associative array without declaring it with declare -A?
AIt works normally
BBash treats it as an indexed array
CBash throws an error
DIt creates a string variable
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.