Insert an element at a certain index in Bash
You can try this:
declare -a arr=("var1" "var2" "var3")i=1arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")echo "${arr[@]}"
result will be:
var1 new var2 var3
More details: How to slice an array in Bash
There is a shorter alternative. The += operator allows overwriting consequent array elements starting from an arbitrary index, so you don't have to update the whole array in this case. See:
$ foo=({1..3})$ declare -p foodeclare -a foo=([0]="1" [1]="2" [2]="3")$$ i=1$ foo+=([i]=bar "${foo[@]:i}")$ declare -p foodeclare -a foo=([0]="1" [1]="bar" [2]="2" [3]="3")