# empty
myArray=()
# with elements
myArray=("first" "second" "third item" "fourth")
myArray=(
"first"
"second"
"third item"
"fourth"
)
# all elements - space delimited
$ echo ${myArray[@]}
# all elements - separate words
$ echo "${myArray[@]}"
# all elements - single word, separated by first character of IFS
$ IFS="-"
$ echo "${myArray[*]}"
# specific element
$ echo "${myArray[1]}"
# two elements, starting at second item
$ echo "${myArray[@]:1:2}"
# keys (indicies) of an array
$ echo "${!myArray[@]}"
myArray=()
myArray+=("item")
# element count
$ echo "${#myArray[@]}"
# length of specific element (string length)
$ echo "${#myArray[1]}"
for arrayItem in "${myArray[@]}"; do
echo "$arrayItem"
done
Note
Named reference to another variable (local -n
) only supported with Bash 4.3.x
or above.
function myFunction {
local -n givenList=$1
echo "${givenList[@]}"
}
itemList=("first" "second" "third")
myFunction itemList
Note: namerefs only work in bash 4.3.x... I've updated on my fork: https://gist.github.com/pstephens/7d7cfcdcf9f1e0a26f7ffba1e9399ef7/revisions