How can i delete an element in an array and then shift the array in Shell Script?

bash, shell

Solution

Try this:

$ array=( "one two" "three four" "five six" )
$ unset array[1]
$ array=( "${array[@]}" )
$ echo ${array[0]}
one two
$ echo ${array[1]}
five six

Shell arrays aren't really intended as data structures that you can add and remove items from (they are mainly intended to provide a second level of quoting for situations like

arr=( "one two" "three four" )
somecommand "${arr[@]}"

to provide `somecommand` with two, not four, arguments). But this should work in most situations.

Problem

First let me state my problem clearly: Ex: Let's pretend this is my array, (the elements don't matter as in my actual code they vary): ``` array=(jim 0 26 chris billy 78 hello foo bar) ``` Now say I want to remove the following elements: ``` chris 78 hello ``` So I did: `unset array[$i]` while looping through the array. This removes the elements correctly, however, i end up with an array that looks like this: ``` array=(jim 0 26 '' billy '' '' foo bar) ``` I need it to look like this: ``` array=(jim 0 26 billy foo bar) ``` where jim is at index 0, 0@1, 26@2, etc.. How do I delete the elements in the array and move the other elements so that there are no null/empty spaces in the array? Thanks!

Original source