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_elementto add an element at a specific index.
