4

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.

oguz ismail
  • 34,491
  • 11
  • 33
  • 56
Jake12342134
  • 1,191
  • 7
  • 26

2 Answers2

6

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

kvantour
  • 20,742
  • 4
  • 38
  • 51
cn007b
  • 14,506
  • 6
  • 48
  • 62
  • 2
    Note that the offset and length parts of `${var:offset:length}` expansion are arithmetic, so the `$` is not strictly required there: `${arr[@]:i}` etc – glenn jackman Dec 17 '20 at 14:43
2

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")
oguz ismail
  • 34,491
  • 11
  • 33
  • 56