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
  • 1
  • 16
  • 47
  • 69
Jake12342134
  • 1,539
  • 1
  • 18
  • 45

2 Answers2

7

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
  • 25,269
  • 4
  • 47
  • 72
cn007b
  • 16,596
  • 7
  • 59
  • 74
  • 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
  • 1
  • 16
  • 47
  • 69