Introduction
We add or remove elements in lists or arrays to change what data we work with. This helps us update information easily.
We add or remove elements in lists or arrays to change what data we work with. This helps us update information easily.
# Adding an element to an array array+=("new_element") # Removing an element by index unset 'array[index]'
fruits=(apple banana cherry)
fruits+=(orange)
echo "${fruits[@]}"fruits=(apple banana cherry orange) unset 'fruits[1]' echo "${fruits[@]}"
numbers=() numbers+=(10) numbers+=(20) numbers+=(30) echo "${numbers[@]}"
This script shows how to add "yellow" to the colors array and remove "green" by its index. Then it prints all remaining colors.
#!/bin/bash # Create an array of colors colors=(red green blue) # Add a new color colors+=(yellow) # Remove the second color (green) unset 'colors[1]' # Print all colors for color in "${colors[@]}"; do echo "$color" done
When you remove an element with unset, the array index is removed but the array keeps its other elements.
After removing elements, indexes may not be continuous. Use loops over "${array[@]}" to avoid index issues.
Use array+=("element") to add elements to an array.
Use unset 'array[index]' to remove elements by their position.
Loop over ${array[@]} to access all current elements safely.
"apple" to the end of a Bash array named fruits?array+=("element").colors?unset command with the array element's index to remove it.unset colors[2], which is correct. Options A, C, and D are not valid Bash commands for removing array elements.items=("pen" "pencil" "eraser")
items+=("marker")
unset 'items[1]'
for item in "${items[@]}"; do
echo "$item"
done${items[@]} skips unset indices, so output is "pen", "eraser", "marker" each on a new line.nums:
nums=(1 2 3 4)
unset nums(0)
echo "${nums[@]}"unset 'array[index]' with square brackets, not parentheses.unset nums(0), which is invalid syntax. It should be unset 'nums[0]'.tasks=("clean" "cook" "shop" "study"). You want to remove the task "cook" and add "exercise" at the end. Which script snippet correctly does this?unset 'tasks[1]' to remove the second element safely.tasks+=("exercise") to append the new task.Pass the test and this pattern moves unknown