📝 Edit page
âž• Add page
Arrays
Arrays reference in GNU docs.
Overview
$ MONTHS=("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul"
"Aug" "Sep" "Oct" "Nov" "Dec")
Get elements:
$ echo ${MONTHS[9]}
$ echo "${MONTHS[@]}"
Note that using echo
or piping to another command will usually mean all the contents are shown on one line.
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.
Remember to add quotes at the start otherwise spaces will be split over newlines.
for X in "$MY_ARRAY[@]"; do
echo "$X"
done
abc def
ghi
Output all on one line.
for X in "$MY_ARRAY[*]"; do
echo "$X"
done
abc def ghi
Old
For Bash 3 - you need curly 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