0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Delete Element from Array Easily

In Bash, delete an element from an array by index using unset array[index] or by value by filtering with a loop or mapfile and grep -v.
📋

Examples

Inputarray=(apple banana cherry) delete index 1
Outputapple cherry
Inputarray=(dog cat bird cat) delete value 'cat'
Outputdog bird
Inputarray=(one two three) delete index 5 (out of range)
Outputone two three
🧠

How to Think About It

To delete an element from a Bash array, first decide if you want to remove by index or by value. For index, use unset to remove that position. For value, loop through the array and keep only elements that don't match the value you want to delete.
📐

Algorithm

1
Get the array and the element to delete (by index or value).
2
If deleting by index, use <code>unset</code> on that index.
3
If deleting by value, create a new array with elements not equal to the value.
4
Replace the original array with the filtered array.
5
Print or return the updated array.
💻

Code

bash
array=(apple banana cherry banana)

# Delete element by index (e.g., index 1)
unset 'array[1]'

# Re-index array to remove gaps
array=(${array[@]})

echo "After deleting index 1: ${array[@]}"

# Delete element by value (e.g., 'banana')
value_to_delete="banana"
new_array=()
for item in "${array[@]}"; do
  if [[ "$item" != "$value_to_delete" ]]; then
    new_array+=("$item")
  fi
 done
array=(${new_array[@]})

echo "After deleting value 'banana': ${array[@]}"
Output
After deleting index 1: apple cherry banana After deleting value 'banana': apple cherry
🔍

Dry Run

Let's trace deleting index 1 and then deleting value 'banana' from the array (apple banana cherry banana).

1

Initial array

array=(apple banana cherry banana)

2

Delete element at index 1

unset 'array[1]' results in array=(apple '' cherry banana)

3

Re-index array

array=(${array[@]}) results in array=(apple cherry banana)

4

Delete elements with value 'banana'

Loop keeps apple and cherry, removes banana

5

Final array

array=(apple cherry)

StepArray Content
Initialapple banana cherry banana
After unset index 1apple '' cherry banana
After re-indexapple cherry banana
After deleting 'banana'apple cherry
💡

Why This Works

Step 1: Using unset to remove by index

The unset array[index] command removes the element at the given index but leaves a gap, so re-indexing is needed.

Step 2: Re-indexing the array

Assigning array=("${array[@]}") compacts the array, removing empty spots left by unset.

Step 3: Filtering by value

Looping through the array and adding only elements not equal to the target value creates a new array without that value.

🔄

Alternative Approaches

Using grep to filter values
bash
array=(apple banana cherry banana)
value_to_delete="banana"
mapfile -t array < <(printf "%s\n" "${array[@]}" | grep -v -x "$value_to_delete")
echo "Filtered array: ${array[@]}"
This method is concise but uses external commands and may be slower for large arrays.
Using a while loop with read
bash
array=(apple banana cherry banana)
value_to_delete="banana"
new_array=()
while IFS= read -r item; do
  [[ "$item" != "$value_to_delete" ]] && new_array+=("$item")
done < <(printf "%s\n" "${array[@]}")
array=(${new_array[@]})
echo "Filtered array: ${array[@]}"
This approach avoids grep but is more verbose.

Complexity: O(n) time, O(n) space

Time Complexity

Deleting by index with unset is O(1), but re-indexing the array is O(n) because it copies all elements. Deleting by value requires scanning all elements, so O(n).

Space Complexity

Re-indexing or filtering creates a new array, so space is O(n) proportional to the array size.

Which Approach is Fastest?

Using unset plus re-indexing is fastest for index deletion. For value deletion, looping in Bash is efficient; using external commands like grep adds overhead.

ApproachTimeSpaceBest For
unset + re-indexO(n)O(n)Deleting by index
Loop filter in BashO(n)O(n)Deleting by value
grep filterO(n)O(n)Concise value deletion, less portable
💡
Use unset array[index] to remove by index and re-index the array to avoid gaps.
⚠️
Forgetting to re-index the array after unset leaves empty elements and unexpected gaps.