How to add elements to an array?

QuestionsQuestions4 SkillsProShell ArraysOct, 20 2025
0113

In Bash, you can add elements to an array using the += operator or by specifying the index directly. Here are both methods:

Method 1: Using the += Operator

You can append elements to the end of an array using the += operator.

# Declare an array
my_array=(apple banana)

# Add elements using +=
my_array+=(cherry date)

# Display the updated array
echo "${my_array[@]}"  # Outputs: apple banana cherry date

Method 2: Specifying the Index

You can also add elements by specifying the index directly.

# Declare an array
my_array=(apple banana)

# Add an element at a specific index
my_array[2]=cherry  # Adds cherry at index 2

# Display the updated array
echo "${my_array[@]}"  # Outputs: apple banana cherry

Summary

  • Use my_array+=(new_element) to append elements to the end of the array.
  • Use my_array[index]=new_element to add an element at a specific index.

0 Comments

no data
Be the first to share your comment!