In Bash, you can remove an element from an array using the unset command. Here’s how you can do it:
Syntax
unset array_name[index]
Example
Suppose you have an array named fruits:
fruits=("Apple" "Banana" "Cherry")
If you want to remove "Banana" (which is at index 1), you would do:
unset fruits[1]
Resulting Array
After running the unset command, the fruits array will look like this:
echo ${fruits[@]} # Outputs: Apple Cherry
Note
- The index of the removed element will leave a "gap" in the array. If you want to re-index the array (i.e., remove the gap), you can create a new array or use a loop to rebuild it.
Re-indexing Example
Here’s how you can re-index the array after removing an element:
# Create a new array without the unset element
new_fruits=()
for fruit in "${fruits[@]}"; do
if [[ -n $fruit ]]; then
new_fruits+=("$fruit")
fi
done
fruits=("${new_fruits[@]}")
Now, fruits will be re-indexed without any gaps.
If you have any more questions or need further clarification, feel free to ask!
