Advanced Bash Scripting

Arrays

Remove

In this lesson, you’ll learn two key operations for managing Bash arrays:

  1. Removing a specific element by its index
  2. Clearing all elements in one command

The image is a slide titled "Arrays remove," showing two checked items: "How to remove a specific element from an array" and "How to remove all of the elements from an array in one shot."

Removing a Specific Element by Index

To delete a single entry in a Bash array, use unset with the array name and the target index:

#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset 'servers[1]'
echo "Remaining elements: ${servers[@]}"

Running this script produces:

$ ./removing.sh
server1 server3

Note

Bash does not reindex arrays after removal. The original indices remain, leaving gaps in the sequence.

To view both values and their indices after deletion:

#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset 'servers[1]'
echo "Values : ${servers[@]}"
echo "Indices: ${!servers[@]}"
$ ./removing_indices.sh
Values : server1 server3
Indices: 0 2

Clearing All Elements

If you need to empty an array completely, omit the brackets when using unset:

#!/usr/bin/env bash
declare -a servers=("server1" "server2" "server3")
unset servers
echo "After clearing: ${servers[@]}"
$ ./removing_all.sh

No output appears because the array has been removed.

Warning

Using unset array deletes the entire variable. You must redeclare it before adding new elements.

Summary of Removal Operations

OperationCommand UsageResult
Remove by indexunset 'array[index]'Deletes the specified element only
Clear entire arrayunset arrayRemoves all elements and the variable

Watch Video

Watch video content

Previous
Insert
Next
Sort