Array Parameters

An array parameter is simply a variable in zsh that holds a list of zero or more items.

The two easiest ways to assign a value to an array parameter are:

array_name=(value1 value2 ... valueN)
set -A array_name value1 value2 .. valueN

Single Element Subscripts

subscripts are used to select one of more individual items from an array. zsh's mechanism for subscripting into arrays is so powerful, it can be considered superior to many programming languages.

The simplest form is:

some_array[expr]

This uses arithmetic expansion to evaluate expr to an integer n. n is then used to return the nth element from the array. (1)

Any subscript n that evaluates to a negative integer will take the nth element from the END of the array:

ARGV[-2]

will return the second-to-last element in the ARGV array parameter.

There are two special subscripts, [@] and [*] that return a list of all of the items in an array. (2)

Obtaining Multiple Consecutive Elements

The next form of subscripting is used to obtain multiple, consecutive elements in an array:

some_array[expr1,expr2]

This returns elements (in some_array) starting from expr1, up to and including expr2. Again, the expressions are evaluated to integers before being used, and negative numbers are used in the same way as descibed above.

Some quick examples:

  > friends=(c_hong bongus hizatch sh_izzo sh_long mufastaf)
  > echo $friends
  c_hong bongus hizatch sh_izzo sh_long mufastaf
  > echo $friends[2,-1]
  bongus hizatch sh_izzo sh_long mufastaf
  > echo $friends[-4,-2]
  hizatch sh_izzo sh_long
  > echo $friends[-4,3]
  hizatch
  > echo $friends[5,-4]
  
  >
  

Subscripts can be included with variable names inside curly braces...

${friends[2,5]} (3)

Replacing Portions of Arrays

If a subscript is used on the left hand side of an assignment, the entire range is replaced by the expression on the right. (4)

An example:

  
  > veg=(lettuce carrot celery tomato onion)
  > echo $veg
  lettuce carrot celery tomato onion
  > veg[4]=(pepper radish)
  > echo $veg
  lettuce carrot celery pepper radish onion
  
  

Subscripting Strings

This item is not quite related to arrays, but it's too useful to pass up.

Subscripting may also be performed on non-array values. With this usage, the subscript specifies a substring to extract from a variable. (As opposed to a list of elements from an array)

Some examples:

  > pain=cluster
  > echo $pain
  cluster
  > echo $pain[3]
  u
  > echo $pain[2,5]
  lust
  > echo $pain[-6,7]
  luster
  > unset pain
  >