- Remove a specific element from an array.
- Remove all elements (clear the entire array).
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):1 and print the remaining elements.
unset servers[1]removes the element with index1. 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:
Remove the entire array
To delete the entire array variable and all its elements:Quick reference
Summary
- Use
unset array[index]to remove a single element. Remaining indices are preserved (no automatic reindexing). - Use
unset arrayto 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.
