0
0
Bash Scriptingscripting~5 mins

Adding and removing elements in Bash Scripting

Choose your learning style9 modes available
Introduction

We add or remove elements in lists or arrays to change what data we work with. This helps us update information easily.

When you want to add a new item to a list of tasks in a script.
When you need to remove a finished or unwanted item from a list.
When managing user inputs stored in an array and updating it dynamically.
When processing files and you want to keep track of files added or removed.
When automating system checks and you want to update the list of servers or services.
Syntax
Bash Scripting
# Adding an element to an array
array+=("new_element")

# Removing an element by index
unset 'array[index]'
Use parentheses and += to add elements to an array.
Use unset with the element's index to remove it from the array.
Examples
This adds "orange" to the fruits array and prints all fruits.
Bash Scripting
fruits=(apple banana cherry)
fruits+=(orange)
echo "${fruits[@]}"
This removes the second element (banana) from the fruits array and prints the rest.
Bash Scripting
fruits=(apple banana cherry orange)
unset 'fruits[1]'
echo "${fruits[@]}"
Starts with an empty array and adds three numbers one by one.
Bash Scripting
numbers=()
numbers+=(10)
numbers+=(20)
numbers+=(30)
echo "${numbers[@]}"
Sample Program

This script shows how to add "yellow" to the colors array and remove "green" by its index. Then it prints all remaining colors.

Bash Scripting
#!/bin/bash

# Create an array of colors
colors=(red green blue)

# Add a new color
colors+=(yellow)

# Remove the second color (green)
unset 'colors[1]'

# Print all colors
for color in "${colors[@]}"; do
  echo "$color"
done
OutputSuccess
Important Notes

When you remove an element with unset, the array index is removed but the array keeps its other elements.

After removing elements, indexes may not be continuous. Use loops over "${array[@]}" to avoid index issues.

Summary

Use array+=("element") to add elements to an array.

Use unset 'array[index]' to remove elements by their position.

Loop over ${array[@]} to access all current elements safely.