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.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With