0
0
Bash Scriptingscripting~20 mins

Adding and removing elements in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output after adding an element to an array?
Consider the following Bash script that adds an element to an array. What will be the output?
Bash Scripting
arr=(apple banana cherry)
arr+=(date)
echo "${arr[@]}"
Aapple banana cherry date
Bapple banana cherry
Capple banana cherry date date
Ddate
Attempts:
2 left
💡 Hint
Remember that += adds elements to the end of the array.
💻 Command Output
intermediate
2:00remaining
What happens when you remove an element from an array by index?
Given this Bash script, what will be the output?
Bash Scripting
arr=(red green blue yellow)
unset arr[1]
echo "${arr[0]} ${arr[1]} ${arr[2]} ${arr[3]}"
Ared blue yellow
Bred green blue yellow
Cred green yellow
Dred blue yellow
Attempts:
2 left
💡 Hint
unset removes the element but does not reindex the array.
📝 Syntax
advanced
2:00remaining
Which option correctly removes the first element from a Bash array?
You want to remove the first element from the array 'arr'. Which command does this correctly?
Bash Scripting
arr=(one two three four)
Aarr=(${arr[1:]})
Barr=(${arr[@]} - 1)
Carr=(${arr[@]:1})
Dunset arr[0]
Attempts:
2 left
💡 Hint
Use array slicing to skip the first element.
🔧 Debug
advanced
2:00remaining
Why does this script fail to remove an element correctly?
Look at this script and find why it does not remove the element 'orange' from the array.
Bash Scripting
fruits=(apple orange banana)
for i in "${!fruits[@]}"; do
  if [[ "${fruits[i]}" == "orange" ]]; then
    unset fruits[$i]
  fi
done
echo "${fruits[0]} ${fruits[1]} ${fruits[2]}"
AThe unset command should use ${fruits[i]} instead of fruits[i]
BThe array is not reindexed after unset, so the output has a blank space
CThe loop variable i is quoted, causing it to be a string instead of an index
DThe if condition syntax is incorrect
Attempts:
2 left
💡 Hint
unset removes the element but does not shift the array indices.
🚀 Application
expert
3:00remaining
How to add multiple elements to a Bash array in one command?
You have an array: arr=(cat dog). You want to add 'bird' and 'fish' at once. Which command does this correctly?
Aarr+=(bird fish)
Barr+=('bird fish')
Carr=(${arr[@]} bird fish)
Darr=(${arr} bird fish)
Attempts:
2 left
💡 Hint
Use += with parentheses to add multiple elements as separate items.