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 "[EMAIL PROTECTED]"; do if test "$v"; then 
> var2+=("$v"); fi; done
>     bash-3.2$ echo [EMAIL PROTECTED]
>     3
>     bash-3.2$ printf '%s\n' "[EMAIL PROTECTED]"
>     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 "[EMAIL PROTECTED]"; do
  [ -n "${var1[$i]}" ] || unset "var1[$i]"
done

For comparison,

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

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

var1=($var1)
because $var1 expands to the list of non-empty elements in the
array by default (you need "[EMAIL PROTECTED]" to include the empty
ones).

In zsh,

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

And with an associative array such as:

typeset -A h
h[foo]=bar
h[empty]=""

To remove the empty ones:

h=("${(kv@)h[(R)?*]}")

for instance.

-- 
Stéphane


Reply via email to