Arrays reference in GNU docs.

Overview

MONTHS=("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" 
  "Aug" "Sep" "Oct" "Nov" "Dec")
echo ${MONTHS[1]}
echo ${MONTHS[@]}

Create

Create using brackets and spaces:

X=()

X=(abc def ghi)

Or newlines.

X=(abc
def
ghi)

Or the old style.

declare -A X

Slice

Get one element

Any invalid index here returns nothing and also a success code.

In ZSH the index starts at 1.

echo ${MONTHS[1]}
# Jan
echo ${MONTHS[4]}
# Apr

Bash

In Bash it starts at 0.

echo ${MONTHS[0]}
# Jan
echo ${MONTHS[3]}
# Apr

Get all

echo $MONTHS[@]
# Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Iterate

Given array:

MY_ARRAY=(abc def ghi)

New syntax

ZSH and Bash 4.

for X in $MY_ARRAY[@]; do
  echo $X
done
abc
def
ghi

Old

For Bash 3 - you need braces. Otherwise you’ll only get the first element.

for X in ${MY_ARRAY[@]}; do
  echo $X
done

Or without an array variable:

for X in abc def ghi; do
  echo $X
done
abc
def
ghi

Modify array

X[2]=zzz
echo $X[2]
# zzz

Convert arguments to an array

MY_ARRAY=("$@")

Based on this StackOverflow thread.

Strings

You can also slice a string.

X=abc
echo "$X[1]"
# a
echo "$X[2]"
# b
echo "$X[@]"
# abc