FUNDAMENTALS A Complete Guide for Beginners
![icon linux](https://linuxsimply.com/wp-content/uploads/2024/05/Linux-Mascot.png)
You can use the following 4 methods to append to an array in Bash:
- Using the shorthand operator (+=):
array_name+=('element to append')
. - Defining the last index:
array_name[${#array_name[@]}]='element to append'
. - Using bracket ():
array_name=(${array_name[@]} 'element to append')
. - Via array concatenation:
array1=(${array1[@]} ${array2[@]})
.
Append to an array in Bash refers to adding elements to a Bash array. It is a fundamental yet essential operation for the seamless addition of data within the array data structure. This article discusses 4 easy methods on how to append to an array in Bash. It discusses the appending of single elements to an array as well as appending multiple elements to a Bash array. It also mentions the methods to append an entire array to another array. Additionally, it mentions 2 common mistakes that may occur during the append operation in Bash arrays with solutions and tips.
1. Using the Shorthand Operator “+=”
Use the +=
operator to append elements to a Bash array. The full syntax is like the following:
array+=(elements_to_append)
Let’s see a simple example of appending to an array in bash using the += operator:
#!/bin/bash
#The main array
digit=(one two three)
#prints array with 3 existing elements
echo "array before appending: ${digit[@]}"
#new value to append
digit+=(four)
#Prints array with newly added element four
echo "array after appending: ${digit[@]}"
In this script after the declaration of the array digit with 3 items, the expression digit+=(four)
adds the new element four to the end of the array. This is evident after printing the array using the echo command.
Append Multiple Elements
Apart from appending a single element to an array, it might become necessary to append multiple elements to a Bash array. Fortunately, Bash arrays provide the following syntax to append more than one element:
array_name+=(element1 element2 elementN)
Here’s an example of appending multiple elements to a Bash array:
#!/bin/bash
#The main array
digit=(one two three)
#prints array with 3 existing elements
echo "array before appending: ${digit[@]}"
#new value to append
digit+=(four five six seven)
#Prints array with newly added element four
echo "array after appending: ${digit[*]}"
In the script, the expression digit+=(four five six seven)
adds 4 new elements (four five six seven) at once to the existing array digit with 3 elements. Finally, prints the array twice to verify multiple appending to the array.
See from the above image that the script appends 4 new elements to the array digit.
Note: Though using the += operator is a very simple and fast method to append to an array, remaining cautious is recommended. For instance, using the = instead of the =+ operator can potentially overwrite the array. So, always ensure that you are using the correct, += operator, to append to a Bash array.
2. Defining the Last Index
Another simple way to append an element to an array is to add data explicitly to the last index. Now, to append an element using the last index, use the expression ${#array_name[@]} with the syntax: array_name[${#array_name[@]}]="Data to append"
. This will append the new Data to append to the end of the array by defining the last index. Here’s an example:
#!/bin/bash
#Main Array to work with
Linux=("Ubuntu" "Debian" "openSUSE")
#print main array
echo "Before append: ${Linux[*]}"
#Value RHEL to append
Linux[${#Linux[@]}]="RHEL"
#Printing the values of an array
echo "After append: ${Linux[*]}"
The above script declares the array Linux with 3 elements using Linux=("Ubuntu" "Debian" "openSUSE")
. Then, in the expression, Linux[${#Linux[@]}]="RHEL"
, ${#Linux[@]} finds out the total number of array elements which is 3 and this is used as the index of the fourth element. Thus, effectively the final expression becomes Linux[3]="RHEL"
that appends RHEL to the Linux array as the end-most element.
3. Append an Array Using Parenthesis
An array element can be appended by using the array variable name and the new element value enclosed within the first bracket (). The full syntax is: array_name=(${array_name[@]} "element to append")
.
Below is an example script to append a value to a Bash array using first brackets ():
#!/bin/bash
# Declare a string array
fruit=("orange" "watermelon" "apple")
#print the array
echo "before append: ${fruit[@]}"
# Add new element at the end of the array using parenthesis ()
fruit=(${fruit[@]} "grape")
#print the array elements in a single line
echo "After append: ${fruit[@]}"
In the script, after the initialization of the array fruit=("orange" "watermelon" "apple")
, the expression fruit=(${fruit[@]} "grape")
first expands the original array and then appends grape as the new element at the end (after index 3). As a result, the fruit array now has 4 elements that are visible after printing the array using the command echo "After append: ${fruit[@]}"
.
Terminal output to append to an array using first brackets ().
Note: To append multiple items using brackets, mention more than one element in the syntax above like this format: array_name=(${array_name[@]} "element1" "element2" "elementN")
4. Using Array Concatenation
Array concatenation is the process of combining two arrays to form a single array. This is very easy to achieve using the syntax array1=(${array1[@]} ${array2[@]})
which will expand and concatenate array1 and array2 into array1. Let’s see array concatenation into action to append elements to a Bash array:
#!/bin/bash
#main array
digit=(1 2 3)
#print array
echo "array1: ${digit[@]}"
#array elements to append
alsoDigit=(5 6 7)
#print array2
echo "array2: ${alsoDigit[@]}"
#array appending via array concatenation
digit=(${digit[@]} ${alsoDigit[@]})
#print the new array
echo "the new array: ${digit[@]}"
Here, The two arrays digit and alsoDigit are expanded and concatenated inside the existing array-type variable digit. After printing the arrays, it’s clear that the concatenation method appends elements to the Bash array.
Upon execution, the script prints both individual & concatenated arrays.
Note: To concatenate and append two arrays to a new array variable, use, for instance, the syntax: Numbers=(${digit[@]} ${alsoDigit[@]})
How to Append Array to Another Array in Bash?
Apart from appending individual or multiple data elements, the smart approach of using the shorthand operator += is capable of appending an array to another array. The complete syntax is array1+=(${array2[@]})
where the += operator appends the array2 to the existing array1.
Here’s how to append an array to another array in Bash:
#!/bin/bash
# Main array
main_array=("Apple" "Orange" "Banana")
echo "main array: ${main_array[@]}"
# Array to append
to_append=("Grapes" "Mango")
echo "to_append: ${to_append[@]}"
# append array to array using compound assignment +=
main_array+=("${to_append[@]}")
# Print the updated array
echo "updated array: ${main_array[@]}"
In the script, the array to_append is successfully appended by using the expression main_array+=("${to_append[@]}")
to the existing main_array with initially 3 elements. Finally, printing the array in the terminal shows that the array contains 5 elements with 2 new elements at the end.
2 Ways to Avoid Common Mistakes When Appending to Bash Arrays
The append operation in Bash array is very simple which you already have learned. However, you might encounter 2 common pitfalls during appending to Bash arrays and employ solutions like the following:
1. Handling Spaces in Bash Array Elements
One common issue arises when you have to handle array elements containing spaces. Look at the below example:
tennis=("nadal" "roddick" "roger federer")
tennis+=("sampras" "suffin")
echo ${tennis[*]}
echo "length: ${#tennis[*]}"
In the above example, when the array elements and length are printed, Bash treats ‘roger federer’ as a single element, which is desirable in this case.
However, if the multi-word element is not quoted around, then it will be treated as 2 other elements rather than a single one like the following:
#!/bin/bash
tennis=("nadal" "roddick" roger federer)
tennis+=("sampras" "suffin")
echo ${tennis[*]}
echo "length: ${#tennis[*]}"
In the above image, the array length is now 6 instead of 5 since Bash treats roger and federer as 2 different array elements due to the absence of quotes around.
Solution: Always use quotes around array elements that contain space to ensure Bash treats them as a single data value.
2. Escape Overwriting Existing Arrays
Another common error is mistakenly using the equal sign (=) instead of the += operator in the array append syntax where the syntax becomes array=(element to append)
and accidentally overwrites the array instead of appending it. See the script below:
#!/bin/bash
tennis=('nadal' 'roddick' 'federer')
tennis=('sampras' 'suffin')
echo ${tennis[*]}
The above script prints sampras suffin instead of printing all the 5 elements nadal roddick federer sampras suffin since the use of = in the syntactical format tennis=(‘sampras’ ‘suffin’) has overwritten the previous array with 2 elements.
Solution: Double-check to make sure you are using the += operator in appending to the array. Otherwise, you might accidentally end up overwriting the array.
Conclusion
This article discusses the concept of how to append to arrays in Bash with 4 different methods. It mentions appending single, or multiple elements to an array. it sheds light on the advanced concept of appending arrays to another Bash array. In addition, it mentions 2 common pitfalls with effective solutions to ensure smooth appending to Bash arrays. Hope this article aids your journey to mastering Bash arrays.
Frequently Asked Questions
How to add elements to a Bash array at specific positions?
To add an element to a Bash array at a specific position, use the concept of direct index assignment with the syntax array_name[index]=value. For instance, to add an element named apple at the 5th position (index 4) to the array food=(rice meat wheat)
, use the syntax food[4]=apple
.
Can I append an array to another array in Bash?
Yes, to append an array to another array, use the <strong>+=</strong>
operator with the syntax new_array+=(${array[@]})
to append array to new_array. Here’s a script for example:
#!/bin/bash
arr1=("apple" "banana" "cherry")
arr2=("mango" "grape")
arr1+=(${arr2[@]})
echo ${arr1[@]}
Output: apple banana cherry mango grape
What’s the difference between array+=element and array+=(element)?
The first syntax array+=element adds a string element to the first element while the latter one appends element as a new individual value at the end of the array. Take the array num=(1 2 3)
for example. The syntax num+=4
will add 4 as a string at the end of the element 1. However, the syntax num+=(4)
will add 4 as a new array element to the end of the array. See the below Bash script:
#!/bin/bash
num=( 1 2 3)
num+=4
num+=(4)
echo ${num[@]}
How do I append to an array in Bash?
To append to an array in Bash, use the “+=” operator, with the syntax, your_array+=(element_To_add)
. This allows you to add an element to the end of an array.
Is it possible to append multiple arrays to another Bash array?
Yes, to append multiple arrays to another array, use +=
with the syntax array1+=("${array2[@]}" "${array3[@]}" "${array4[@]}")
to append the 3 arrays (array2 array3 array4) to the existing array1.
What is meant by Bash array append?
Bash array append means to add elements to an array in Bash. The append operation adds elements at the end of an existing array. To append an element to a Bash array, use the shorthand operator += with the syntax array_name+=(element to append). For example, the syntax cars+=(honda)
adds the element honda to the end of the array cars.
Related Articles
- How to Convert a JSON Array into Bash Array [5 Methods]
- Master Bash Array of Strings with Spaces [Complete Guide]
- How to Convert String into Array in Bash [8 Methods]
- How to Clear an Array in Bash [6 Methods]
- How to Filter an Array in Bash? [8 Methods]
- How to Copy an Array in Bash [6 Simple Methods]
- How to Reverse an Array in Bash? [8 Easy Methods]
- How to Slice an Array in Bash [10 Simple Methods]
- Iterate Through a Bash Array Using “foreach” Loop [5 Examples]
- How to Check If an Array is Empty in Bash? [5 Methods]
<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial