Search code examples
arraysshellzsh

Remove entry from array


I want to do sth. like this:

foo=(a b c)
foo-=b
echo $foo # should output "a c"

How can I remove an entry from an array? foo-=b does not work.

The removal should work no matter where the entry is.


Solution

  • To remove element number $i: a=("${(@)a[1,$i-1]}" "${(@)a[$i+1,$#a]}")

    (The simpler construct a=($a[1,$i-1] $a[$i+1,-1]) also removes empty elements.)

    ADDED:

    To remove any occurence of b: a=("${(@)a:#b}")
    :# is the hieroglyph to remove matching elements; "" and (@) is to operate correctly on arrays even if they contain empty elements.