tags:

views:

119

answers:

2

e.g. looking for something like:

foo() { echo ${1[2]} '\n'; }

a=(abc def ghi) foo $a

--> def

Or ideally:

foo (abc def ghi)

A: 

Figured out a workaround:

foo() {
  local a=$1
  local b=$2

  echo ${(j:---:)${=b}}

  foreach d in ${${=b}}
  do
      echo $d
  done
}

Where parameter2 is a string of white-separated text, e.g. 'a badkljf odod'

Aaron F.
+1  A: 

You can't. Functions take positional parameters like any other command.

Note also that your workaround doesn't allow any of the "array" elements to contain whitespace.

The cleanest thing I can think of is to require that the caller create a local array, then read it from the function:

$ foo() {
   for element in $FOO_ARRAY
   do
       echo "[$element]"
   done
}
$ local FOO_ARRAY; FOO_ARRAY=(foo bar baz quux)
$ foo
[foo]
[bar]
[baz]
[quux]

I know bash does similar acrobatics for its completion system, and I think zsh might, too. It's not too unusual.

Eevee