0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Insert Element in Array with Example

In Bash, insert an element into an array at position i by slicing and combining: array=("${array[@]:0:i}" "$new_element" "${array[@]:i}").
📋

Examples

Inputarray=(a b c); insert 'x' at position 1
Outputa x b c
Inputarray=(1 2 3 4); insert '99' at position 0
Output99 1 2 3 4
Inputarray=(foo bar); insert 'baz' at position 5 (beyond end)
Outputfoo bar baz
🧠

How to Think About It

To insert an element in a Bash array, split the array into two parts: before and after the insertion index. Then create a new array by joining the first part, the new element, and the second part. This way, the new element fits exactly where you want.
📐

Algorithm

1
Get the original array and the element to insert.
2
Get the position where to insert the element.
3
Split the array into two slices: before and after the position.
4
Create a new array by combining the first slice, the new element, and the second slice.
5
Replace the original array with the new array.
💻

Code

bash
array=(a b c d)
new_element=x
pos=2
array=("${array[@]:0:pos}" "$new_element" "${array[@]:pos}")
echo "${array[@]}"
Output
a b x c d
🔍

Dry Run

Let's trace inserting 'x' at position 2 in array (a b c d).

1

Original array and inputs

array=(a b c d), new_element='x', pos=2

2

Slice before position

"${array[@]:0:2}" gives (a b)

3

Slice after position

"${array[@]:2}" gives (c d)

4

Combine slices with new element

New array = (a b x c d)

StepArray Content
Initiala b c d
After insertiona 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

Using a loop to build a new array
bash
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[@]}"
More verbose but clearer for beginners; less efficient for large arrays.
Appending and swapping elements
bash
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[@]}"
Manually shifts elements to make space; useful if you want to avoid creating new arrays.

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.

ApproachTimeSpaceBest For
Array slicingO(n)O(n)Simple and readable insertion
Loop building new arrayO(n)O(n)Clear logic, beginner-friendly
Manual shiftingO(n)O(n)In-place style, avoids new array creation
💡
Use array slicing to insert elements cleanly without loops in Bash.
⚠️
Forgetting to quote array expansions can cause word splitting and unexpected results.