12 November 2015

unset arr[2] does not remove the third element in BASH array arr the way you might expect: the subscripts of all elements in the array are intact. And, this subtle issue might incur big surprises.

$ arr=(a b c d)

$ echo ${!arr[@]}
0 1 2 3

$ echo ${arr[2]}
c

$ echo ${arr[3]}
d

$ unset arr[2]

$ echo ${!arr[@]}
0 1 3

$ echo ${arr[2]}


$ echo ${arr[3]}
d

Note however, the usual usage of for each works.

$ for each in "${arr[@]}"; do echo "In arr: $each"; done
In arr: a
In arr: b
In arr: d

Remove elements from an array based on index

arr=(a b c d e)
idx=2

arr=(${arr[@]:0:$idx} ${arr[@]:$((idx+1))})

NOTE: unset arr[idx] does not re-arrange subscripts of elements.

Remove elements from an array based on value

elem="todel"
local tmp=()

for each in "${arr[@]}"; do
    [ "$each" != "$elem" ] && tmp+=("$each")
done

arr=("${tmp[@]}")
unset tmp


blog comments powered by Disqus