Using unset to delete array elements

Hi,

I am writing a BASH script. My questions regard deleting elements of arrays.

I have an array:
michael-browns-powerbook-g4-15:~ msb65$ test_array=(1 2 3 4)
michael-browns-powerbook-g4-15:~ msb65$ echo ${test_array[@]}
1 2 3 4

To delete the second element of test_array I type:
michael-browns-powerbook-g4-15:~ msb65$ unset test_array[1]
michael-browns-powerbook-g4-15:~ msb65$ echo ${test_array[@]}
1 3 4

I would like to again delete the second element (which is now 3). So I repeat the previous two lines of code:
michael-browns-powerbook-g4-15:~ msb65$ unset test_array[1]
michael-browns-powerbook-g4-15:~ msb65$ echo ${test_array[@]}
1 3 4

  • Why is it that the second element was not deleted? Am I not deleting array elements properly?

Thanks.
Mike

The elements are not reordered.

for i in 0 1 2 3 
do
   echo "test_array  $i  = ${test_array}"
done

Hi Jim,

I really appreciate your help! Two final questions:

  • When you use unset, you refer to the array with "$" and "{}". When I use them I get an error:
    michael-browns-powerbook-g4-15:~ msb65$ array=(1 2 3 4)
    michael-browns-powerbook-g4-15:~ msb65$ unset ${array[1]}
    -bash: unset: `2': not a valid identifier

The only way I get it work is if I type:
michael-browns-powerbook-g4-15:~ msb65$ unset array[1]

Why is that?. What is the difference between the two methods?

  • Is there any way to just eliminate an array element (ie reorder the array)?

Mike

One way ....

$ test=(1 2 3 4)
$ echo ${test[@]}
1 2 3 4
$ test=( ${test[@]:0:1} ${test[@]:2:2})
$ echo ${test[@]}
1 3 4
$ echo ${test[1]}
3
$