Bash Script to Insert Element in Array with Example
i by slicing and combining: array=("${array[@]:0:i}" "$new_element" "${array[@]:i}").Examples
How to Think About It
Algorithm
Code
array=(a b c d) new_element=x pos=2 array=("${array[@]:0:pos}" "$new_element" "${array[@]:pos}") echo "${array[@]}"
Dry Run
Let's trace inserting 'x' at position 2 in array (a b c d).
Original array and inputs
array=(a b c d), new_element='x', pos=2
Slice before position
"${array[@]:0:2}" gives (a b)
Slice after position
"${array[@]:2}" gives (c d)
Combine slices with new element
New array = (a b x c d)
| Step | Array Content |
|---|---|
| Initial | a b c d |
| After insertion | a b x c d |
Why This Works
Step 1: Array slicing
Using ${array[@]:start:length} extracts parts of the array before and after the insertion point.
Step 2: Combining slices
We create a new array by joining the first slice, the new element, and the second slice to insert the element exactly where needed.
Step 3: Replacing original array
Assigning the combined array back to the original variable updates it with the inserted element.
Alternative Approaches
array=(a b c d) new_element=x pos=2 new_array=() for ((i=0; i<${#array[@]}; i++)); do if [[ $i -eq $pos ]]; then new_array+=("$new_element") fi new_array+=("${array[i]}") done array=("${new_array[@]}") echo "${array[@]}"
array=(a b c d) new_element=x pos=2 array+=("") for ((i=${#array[@]}-1; i>pos; i--)); do array[i]=${array[i-1]} done array[pos]="$new_element" echo "${array[@]}"
Complexity: O(n) time, O(n) space
Time Complexity
The operation copies parts of the array to create a new one, so it takes linear time proportional to the array size.
Space Complexity
A new array is created during insertion, so extra space proportional to the array size is used.
Which Approach is Fastest?
Slicing and combining arrays is concise and efficient for small to medium arrays; manual shifting may be faster for very large arrays but is more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Array slicing | O(n) | O(n) | Simple and readable insertion |
| Loop building new array | O(n) | O(n) | Clear logic, beginner-friendly |
| Manual shifting | O(n) | O(n) | In-place style, avoids new array creation |