[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: removing null elements from an array

From: Stephane Chazelas
Subject: Re: removing null elements from an array
Date: Fri, 18 Jul 2008 12:56:13 +0100
User-agent: Mutt/1.5.16 (2007-09-19)

On Thu, Jul 17, 2008 at 11:12:47PM +0000, Poor Yorick wrote:
> To get rid of null elements in an array, I currently do something like this: 
>     bash-3.2$ var1=("with spaces" "more spaces" '' "the end")
>     bash-3.2$ for v in "address@hidden"; do if test "$v"; then var2+=("$v"); 
> fi; done
>     bash-3.2$ echo address@hidden
>     3
>     bash-3.2$ printf '%s\n' "address@hidden"
>     with spaces
>     more spaces
>     the end

A note though: bash arrays are more associative arrays (with
keys limited to positive integers) more than arrays.

If you have a bash array with:
   12 => ""
  123 => foo
 3456 => bar

Your method will turn it into:

    0 => foo
    1 => bar

With recent versions of bash, you could do:

for i in "address@hidden"; do
  [ -n "${var1[$i]}" ] || unset "var1[$i]"

For comparison,

In zsh, arrays are arrays, and there is a difference variable
type for associative arrays (whose keys are not limited to

In zsh, removing the empty elements is just a matter of

because $var1 expands to the list of non-empty elements in the
array by default (you need "address@hidden" to include the empty

In zsh,

on an empty array is the same as
a=("" "" foo)

And with an associative array such as:

typeset -A h

To remove the empty ones:


for instance.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]