How to add/remove an element to/from the array in bash?
Last Updated :
25 Sep, 2023
If we want to operate an element by adding and removing from the array using the bash script, then we can create a custom bash script that will perform the options of adding and removing the elements from the array.
Example:
Choose an option:
1. Print Rainbow Colors
2. Add a Color to the Rainbow
3. Remove a Color from the Rainbow
4. Quit
Enter your choice (1/2/3/4):
Input: 1
Output:
The colors of the rainbow are:
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Here our main task is to write a shell script that uses the predefined array that stores the elements of any entities, and we need to manage these elements through menu menu-driven shell script, where we can perform the operations on elements using these menu-driven choices.
Creating the Script
Step 1: We will start by creating a new file called rainbow.sh using a text editor of your choice. The first thing we will do in our script is to store the elements in the array with the elements as per our choice. For this example, we have taken the array of colors of the rainbow. As per your choice, you can take an array of any elements.
#!/bin/bash
# Defining an array with rainbow colors
rainbow=("Red" "Orange" "Yellow" "Green" "Blue" "Indigo" "Violet")
Step 2: After defining the array with the pre-elements, we need to create a function that will print the elements of the array. We have created a function named (print_rainbow_colours()), and using the for loop in a bash script, we are iterating over the elements and printing one by one using the 'echo' command.
# Function to print the rainbow colors
print_rainbow_colors() {
echo "Colors of the rainbow are:"
for color in "${rainbow[@]}"; do
echo "$color"
done
}
Step 3: We are performing the adding and removing of the array elements, we need to write a function that will add the elements in the array. We have created a function named "add_color_to_rainbow()", this function takes the input as a color name from the user can append the color in the exiting array.
# Function to add a color to the rainbow
add_color_to_rainbow() {
read -p "Colour Name: " new_color
rainbow+=("$new_color")
echo "Added $new_color to the rainbow!"
}
Step 4: The above function was to add the colors or elements in the existing array, but now, we need to write a function that will take input from the user and will delete the element from the array as per the input. We have written a function named "remove_color_from_rainbow())", that takes the input from the user and according to the conditional statement, matches the input with the existing element, if the element is found, then it is removed from the array else if the element is not found, then the array remains unchanged.
# Function to remove a color from the rainbow
remove_color_from_rainbow() {
read -p "Enter a color to remove from the rainbow array: " color_to_remove
if [[ " ${rainbow[*]} " == *" $color_to_remove "* ]]; then
rainbow=("${rainbow[@]/$color_to_remove}")
echo "Removed $color_to_remove from the rainbow array."
else
echo "The color $color_to_remove is not in the rainbow."
fi
}
Step 5: Now, that our functional word is been completed, we need to write a case block that will be menu-driven. Using this menu-driven, the user can select the choice of adding or removing the elements from the array. We have used a while loop to iteratively show the choices to the user and by using the case block we are inputting the calling the function as per the user's choice.
# Main menu
while true; do
echo "Choose an option:"
echo "1. Print Rainbow Colors"
echo "2. Add a Color to the Rainbow"
echo "3. Remove a Color from the Rainbow"
echo "4. Quit"
read -p "Enter your choice (1/2/3/4): " choice
case $choice in
1)
print_rainbow_colors
;;
2)
add_color_to_rainbow
;;
3)
remove_color_from_rainbow
;;
4)
echo "Thank You Geek"
exit 0
;;
*)
echo "Invalid choice. Please enter a valid option (1/2/3/4)."
;;
esac
done
Steps to create and execute a bash script
Step 1: Open the terminal window using the keyboard shortcut "Ctrl + Alt + T".
Step 2: Using any text editor like vim, vi, or nano, open a new blank file in the text editor.
vim rainbow.sh
Step 3: Now, we need to write the below script in the created file rainbow.sh
#!/bin/bash
# Defining an array with rainbow colors
rainbow=("Red" "Orange" "Yellow" "Green" "Blue" "Indigo" "Violet")
# Function to print the rainbow colors
print_rainbow_colors() {
echo "Colors of the rainbow are:"
for color in "${rainbow[@]}"; do
echo "$color"
done
}
# Function to add a color to the rainbow
add_color_to_rainbow() {
read -p "Colour Name: " new_color
rainbow+=("$new_color")
echo "Added $new_color to the rainbow!"
}
# Function to remove a color from the rainbow
remove_color_from_rainbow() {
read -p "Enter a color to remove from the rainbow array: " color_to_remove
if [[ " ${rainbow[*]} " == *" $color_to_remove "* ]]; then
rainbow=("${rainbow[@]/$color_to_remove}")
echo "Removed $color_to_remove from the rainbow array."
else
echo "The color $color_to_remove is not in the rainbow."
fi
}
# Main menu
while true; do
echo "Choose an option:"
echo "1. Print Rainbow Colors"
echo "2. Add a Color to the Rainbow"
echo "3. Remove a Color from the Rainbow"
echo "4. Quit"
read -p "Enter your choice (1/2/3/4): " choice
case $choice in
1)
print_rainbow_colors
;;
2)
add_color_to_rainbow
;;
3)
remove_color_from_rainbow
;;
4)
echo "Thank You Geek"
exit 0
;;
*)
echo "Invalid choice. Please enter a valid option (1/2/3/4)."
;;
esac
done
Step 4: Now, the next task is to make the script executable by running the chmod command in the terminal.
chmod +x rainbow.sh
Step 5: Finally we need to execute the script by using the below command:
./rainbow.sh
Output:
Output of Shell ScriptThe following screenshot of the test case of the code is executed, it takes the input from the user to perform the actions of Printing Rainbow Colors, Adding a color to the Rainbow, and Removing the color from the Rainbow. The following code uses looping, conditional statements, and error handling to manage the operations on the color array. The shell script prompts for the user input and displays the colors of the rainbow in a sequence manner. Also, the shell script allows the user to manage the array to the color by adding and removing the color from the array.
Conclusion
In this article, we have seen how we can create a shell script to perform various array operations like printing the array elements, adding new elements in the existing array, and removing the elements from the array. We have created different functions to perform this operation. Using the looping and conditional statements, we have created a menu-driven script, that uses the user's choice for performing the operations. Shell scripts are the most useful utilities for automating the task and enhancing the workflow.
Similar Reads
JavaScript - How to Remove an Element from an Array?
Removing elements from an array is a fundamental operation in JavaScript, essential for data manipulation, filtering, and transformation. This guide will explore different methods to efficiently remove elements from an array, enhancing your understanding and capability in handling arrays.1. Using po
3 min read
How to delete an Element From an Array in PHP ?
To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element.This article discusses some of the most common methods used i
4 min read
How to remove specific elements from a NumPy array ?
In this article, we will discuss how to remove specific elements from the NumPy Array. Remove specific elements from a NumPy 1D arrayDeleting element from NumPy array using np.delete() The delete(array_name ) method will be used to do the same. Where array_name is the name of the array to be delete
3 min read
How to Remove Duplicate Elements from Array in Ruby?
This article focuses on discussing how to remove duplicate elements from an array in Ruby. In Ruby, an array is a fundamental data structure that stores a collection of elements in a specific order. Various methods and approaches can be used to remove duplicate elements from an array. Removing Dupli
2 min read
How to move an array element from one array position to another in JavaScript?
In JavaScript, we can access an array element as in other programming languages like C, C++, Java, etc. Also, there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another
5 min read
How to remove all nil elements from an Array in Ruby permanently?
In this article, we will discuss how to remove all nil elements from an array permanently in Ruby. We can remove all nil elements from an array permanently through different methods ranging from using compact! method to delete method with nil argument. Table of Content Removing all nil elements from
2 min read
How to Remove Empty String from Array in Ruby?
In this article, we will learn how to remove empty strings from an array in Ruby. We can remove empty strings from an array in Ruby using various methods. Table of Content Remove empty string from array using rejectRemove empty string from array using selectRemove empty string from array using map a
2 min read
How To Delete An Item From State Array in ReactJS?
It is important to manage the state in ReactJS for building interactive user interfaces. Sometimes when we work with arrays, we need to remove an item from these arrays. A common use case is deleting an item from an array stored in the componentâs state. In this article, weâll explore different ways
3 min read
How to Switch the First Element of an Arrays Sub Array in PHP?
Given a 2D array where each element is an array itself, your task is to switch the first element of each sub-array with the first element of the last sub-array using PHP.Example:Input: num = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];Output: [ ['g', 'b', 'c'], ['d', 'e', 'f'], ['a', 'h', '
2 min read
How to Insert a New Element in an Array in PHP ?
In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read