Open In App

How to add/remove an element to/from the array in bash?

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 Script

Output of Shell Script

The 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads