Skip to main content
Let’s talk about removing elements from a Bash array. There are two common removal scenarios:
  • Remove a specific element from an array.
  • Remove all elements (clear the entire array).
Both are done with the unset builtin. Use unset array[index] to remove a single element or unset array to remove the entire array variable.

Remove a specific element

To delete the element at index 1 (the second element):
Example: remove the element at index 1 and print the remaining elements.
Example output:
How Bash handles this:
  • unset servers[1] removes the element with index 1. Bash does not renumber (reindex) the remaining elements; the array may become sparse.
  • When you expand an array with "${servers[@]}", Bash prints the values of existing indices in ascending order, which can make it look like elements were shifted.
Removing an element with unset deletes that specific index; Bash preserves the original index numbers of remaining elements. Expanding "${servers[@]}" prints the present values in index order, so gaps are not visible in the flat expansion.

Demonstrating index access after unset

After removing the element at index 1, accessing that index yields an empty string, while other indices retain their values:
Example output:

Remove the entire array

To delete the entire array variable and all its elements:
Example:
Example output:

Quick reference

Summary

  • Use unset array[index] to remove a single element. Remaining indices are preserved (no automatic reindexing).
  • Use unset array to remove the entire array variable.
  • Inspect individual indices (e.g., ${array[1]}) to detect unset slots.
  • Expanding with "${array[@]}" prints all existing values in index order and hides any gaps.
References:
A slide titled "Arrays remove" on a dark background, featuring a yellow lightbulb icon and a checked box. The box contains the text: "Inserting and removing data are the basic operations we can do to an array."

Watch Video