Create a Array
$ a[0]=foo$ echo ${a[0]}
#!/bin/bashdeclare -a a
$ days=(Sun Mon Tue Wed Thu Fri Sat)
$ days=([0]=Sun [1]=Mon [2]=Tue [3]=Wed [4]=Thu [5]=Fri [6]=Sat)
Any reference to an array variable without a subscript refers to element zero of the array.
Array Operations
Array Contents
${a[*]} ${a[@]} — the most useful
The subscripts * and @ can be used to access every element in an array.
$ animals=("a dog" "a cat" "a fish")$ for i in ${animals[*]}; do echo $i; doneadogacatafish$ for i in ${animals[@]}; do echo $i; doneadogacatafish$ for i in "${animals[*]}"; do echo $i; donea dog a cat a fish$ for i in "${animals[@]}"; do echo $i; donea doga cata fish
Array Length
${#a[@]}
$ echo ${#a[@]} # number of array elements1$ echo ${#a[100]} # length of element 1003
Finding the Subscripts Used by an Array
${!array[*]}
${!array[@]} — the most useful
$ foo=([2]=a [4]=b [6]=c)$ for i in "${foo[@]}"; do echo $i; doneabc$ for i in "${!foo[*]}"; do echo $i; done246$ for i in "${!foo[@]}"; do echo $i; done246
Adding Elements to the End of an Array
a+=(v1 v2 v3)
$ foo=(a b c)$ echo ${foo[@]}a b c$ foo+=(d e f)$ echo ${foo[@]}a b c d e f
Sorting an Array
#!/bin/bash# array-sort: Sort an arraya=(f e d c b a)echo "Original array: ${a[@]}"a_sorted=($(for i in "${a[@]}"; do echo $i; done | sort))echo "Sorted array: ${a_sorted[@]}"
$ array-sortOriginal array: f e d c b aSorted array: a b c d e f
Deleting an Array
unset a —— delete arrayunset 'a[1]' —— delete element of array
The array element must be quoted to prevent the shell from performing pathname expansion.
$ echo ${foo[@]}a b c d e f$ unset foo$ echo ${foo[@]}$$ foo=(a b c d e f)$ echo ${foo[@]}a b c d e f$ unset 'foo[2]'$ echo ${foo[@]}a b d e f
Associative Arrays
Associative arrays use strings rather than integers as array indexes.
Unlike integer indexed arrays, which are created by merely referencing them, associative arrays must be created with the declare command using the new -A option.
bash versions 4.0 and greater support associative arrays.
#!/bin/bashdeclare -A colorscolors["red"]="#ff0000"colors["green"]="#00ff00"colors["blue"]="#0000ff"echo ${colors["blue"]}
