How to remove elements from an array?

QuestionsQuestions8 SkillsProShell ArraysNov, 21 2025
076

To remove elements from an array in Bash, you can use the unset command. Here’s how you can do it:

Example of Removing Elements from an Array:

  1. Declare and Initialize an Array:

    NAMES=("Alice" "Bob" "Charlie" "David")
  2. Remove an Element:
    To remove an element, use the unset command followed by the index of the element you want to remove.

    unset NAMES[1]  # This removes "Bob"
  3. Display the Updated Array:
    You can print the array to see the changes.

    echo "${NAMES[@]}"  # Outputs: Alice Charlie David

Complete Example:

Here’s a complete script demonstrating how to remove an element from an array:

#!/bin/bash

# Declare and initialize an array
NAMES=("Alice" "Bob" "Charlie" "David")

# Remove the second element (Bob)
unset NAMES[1]

# Display the updated array
echo "Updated array: ${NAMES[@]}"

Important Notes:

  • After using unset, the index of the removed element will still exist but will be empty. If you want to re-index the array, you can use a loop or create a new array.
  • The unset command can also be used to remove the entire array by using unset NAMES.

Let me know if you need more information!

0 Comments

no data
Be the first to share your comment!