# HELP unsetting array element in loop

**URL:** <https://community.unix.com/t/help-unsetting-array-element-in-loop/265389>\
**Category:** Shell Programming and Scripting\
**Created:** [May 9, 2010, 9:52pm UTC](https://community.unix.com/t/help-unsetting-array-element-in-loop/265389 "2010-05-09T21:52:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![msf5042](https://community.unix.com/user_avatar/community.unix.com/msf5042/32/5539_2.png) [@msf5042](https://community.unix.com/u/msf5042)\
**Post date:** [May 9, 2010, 9:52pm UTC](https://community.unix.com/t/help-unsetting-array-element-in-loop/265389/1 "2010-05-09T21:52:12Z")

</div>

I have a loop and I need to be able to unset the array element that I am currently accessing in it. I was thinking of making a counter that increments with the loop and doing unset $dirs[$counter] but if I do that I am not sure if the other members of the array would get shifted down in index (meaning that the second time I unset an element I would unset the element in front of the one that I actually want to unset).

Any help is appreciated.

```nohighlight
for x in ${dirs[@]}
do
if [[$x == $dir*]]; then
bool=1
# here I need to do unset $dirs[????]....
fi
done

```

---

<div class="post-metadata">

**Author:** ![pseudocoder](https://community.unix.com/user_avatar/community.unix.com/pseudocoder/32/666_2.png) [@pseudocoder](https://community.unix.com/u/pseudocoder)\
**Post date:** [May 9, 2010, 10:14pm UTC](https://community.unix.com/t/help-unsetting-array-element-in-loop/265389/2 "2010-05-09T22:14:38Z")

</div>

> [@msf5042](#):
>
> I was thinking of making a counter that increments with the loop and doing unset $dirs[$counter]

I don't know if this is an option for you, but you could create another array and store the counter values (array postions which need to be deleted) and do the unset thing in a second for loop when the first for loop ends.

---

<div class="post-metadata">

**Author:** ![frans](https://community.unix.com/user_avatar/community.unix.com/frans/32/1697_2.png) [@frans](https://community.unix.com/u/frans)\
**Post date:** [May 10, 2010, 1:10am UTC](https://community.unix.com/t/help-unsetting-array-element-in-loop/265389/3 "2010-05-10T01:10:44Z")

</div>

You can scan the array this way, so you have the index :

```nohighlight
for ((i=0; i<${#dirs[@]}; i++))
do
    if [[${#dirs[$i]} == $dir* ]]
    then
        bool=1
        # here I need to do unset $dirs[????]....
        ${#dirs[$i]}=""
    fi
done

```
