Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an element at a certain index in Bash

Tags:

bash

I have an array in bash, which is declared as

string='var1/var2/var3';
IFS='/' read -r -a array <<< $string

So the array is ["var1", "var2", "var3"]

I want to add an element at a specified index and then shift the rest of the elements that already exist.

So the resultant array becomes

["var1", "newVar", "var2", "var3"]

I've been trying to do this with and loops but I feel like there's some better more "bash" way of doing this. The array may not be of a fixed length so it needs to be dynamic.

like image 487
Jake12342134 Avatar asked Jan 25 '23 14:01

Jake12342134


2 Answers

You can try this:

declare -a arr=("var1" "var2" "var3")
i=1
arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
echo "${arr[@]}"

result will be:

var1 new var2 var3

More details: How to slice an array in Bash

like image 140
cn007b Avatar answered Jan 27 '23 03:01

cn007b


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 foo
declare -a foo=([0]="1" [1]="2" [2]="3")
$
$ i=1
$ foo+=([i]=bar "${foo[@]:i}")
$ declare -p foo
declare -a foo=([0]="1" [1]="bar" [2]="2" [3]="3")
like image 25
oguz ismail Avatar answered Jan 27 '23 04:01

oguz ismail