Add value at given index without deleting

I really don't know how to use bash, and I have a problem. I usually use python, so I don't know how to do without a list. How to add a value to an array without deleting the default value.

myArray=(5 6 13 14)

For example, I would like to add 9 to index 2, and I want to do this:

myArray=(5 6 9 13 14)

And not that:

myArray=(5 6 9 14)

Obviously, execution is myArray[2]=9not working. I could add it and move everything else from 1 to the left, but I'm trying to do something optimized, so if there is a solution without a loop, I would like to know :)

+4
source share
1 answer

Use slices to capture before and after parts of the array, then create a new array.

n=2
myArray=( "${myArray[@]:0:n}" 9 "${myArray[@]:n}")

, , , .

+5

Source: https://habr.com/ru/post/1619567/


All Articles