# empty
myArray=()
# with elements
myArray=("first" "second" "third item" "fourth")
myArray=(
"first"
"second"
"third item"
"fourth"
)
# all elements (space delimited)
$ echo ${myArray[@]}
# all elements (seperate words)
$ echo "${myArray[@]}"
# all elements (single word, separated by first character of 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
- http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html
- http://www.thegeekstuff.com/2010/06/bash-array-tutorial
- https://www.tecmint.com/working-with-arrays-in-linux-shell-scripting/
- http://www.gnu.org/software/bash/manual/bashref.html#Arrays
- http://wiki.bash-hackers.org/commands/builtin/declare#nameref