0
0
Bash Scriptingscripting~20 mins

Associative arrays (declare -A) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Associative Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of Associative Array Access
What is the output of this Bash script?
Bash Scripting
declare -A colors
colors[apple]=red
colors[banana]=yellow
colors[grape]=purple
echo ${colors[banana]}
Ayellow
Bred
Cpurple
Dbanana
Attempts:
2 left
💡 Hint
Look at the key used inside the brackets when accessing the array.
💻 Command Output
intermediate
2:00remaining
Count Items in Associative Array
What is the output of this Bash script?
Bash Scripting
declare -A animals
animals[dog]=bark
animals[cat]=meow
animals[cow]=moo
animals[duck]=quack
echo ${#animals[@]}
A4
B3
C0
D1
Attempts:
2 left
💡 Hint
${#array[@]} gives the number of elements in the array.
🔧 Debug
advanced
2:00remaining
Identify the Error in Associative Array Declaration
What error does this Bash script produce?
Bash Scripting
colors=( [red]=apple [yellow]=banana )
echo ${colors[red]}
Abash: colors: unbound variable
Bbash: colors: array assignment without declare -A
Cbash: colors: command not found
DNo error, outputs 'apple'
Attempts:
2 left
💡 Hint
Associative arrays require a special declaration in Bash.
🚀 Application
advanced
2:00remaining
Result of Looping Over Associative Array Keys
What will this Bash script output?
Bash Scripting
declare -A capitals
capitals[France]=Paris
capitals[Japan]=Tokyo
capitals[India]=NewDelhi
for country in "${!capitals[@]}"; do
  echo "$country: ${capitals[$country]}"
done
AParis Tokyo NewDelhi
B
Paris: France
Tokyo: Japan
NewDelhi: India
C
France: Paris
Japan: Tokyo
India: NewDelhi
DFrance Japan India
Attempts:
2 left
💡 Hint
"${!array[@]}" gives all keys in the associative array.
🧠 Conceptual
expert
2:00remaining
Behavior of Unset Key in Associative Array
What is the output of this Bash script?
Bash Scripting
declare -A fruits
fruits[apple]=red
fruits[banana]=yellow
unset fruits[apple]
echo ${fruits[apple]:-none}
Ayellow
Bred
Cbanana
Dnone
Attempts:
2 left
💡 Hint
Unset removes the key, and the default value is used if key is missing.