Bash Bonanza Part 4: Arrays

# The following will create an indexed array $ declare -a ARRAY_NAME # The following will create an associative array $ declare -A ARRAY_NAME
# Indexed array $ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')# Associative array $ declare -A ASSOCIATIVE_ARRAY=(['foo']='bar' ['hate']='no' ['love life']='yes')
# Recall that "${VARIABLE_NAME}" is how you would refer to an standard variable. The only difference here are the square brackets.
$ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')
$ echo "${INDEXED_ARRAY[1]}" > super *dangerous* name! $ INDEXED_ARRAY[1]='My name is '"'"'James Bond'"'"'' $ echo "${INDEXED_ARRAY[1]}" > My name is 'James Bond' $ declare -A ASSOCIATIVE_ARRAY=(['foo']='bar' ['hate']='no' ['love life']='yes') $ echo "${ASSOCIATIVE_ARRAY['love life']}" > yes $ ASSOCIATIVE_ARRAY['foo']='I did not eat all the pies' $ echo "${ASSOCIATIVE_ARRAY['foo']}" > I did not eat all the pies
$ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')
$ printf '%s\n' "${INDEXED_ARRAY[*]}" > arr super *dangerous* name! hello $ printf '%s\n' "${INDEXED_ARRAY[@]}" > arr > super *dangerous* name! > hello
$ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')
# note the additional exclamation mark
$ printf '%s\n' "${!INDEXED_ARRAY[*]}"
> 0 1 2

$ printf '%s\n' "${!INDEXED_ARRAY[@]}"
> 0 > 1 > 2
$ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')$ echo "${INDEXED_ARRAY}" > arr
$ declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')# this is just a string $ ARRAY_REFERENCE='INDEXED_ARRAY[@]' 
# "${!ARRAY_REFERENCE}" will first get the value of ARRAY_REFERENCE, and then get *its* value
# "${!ARRAY_REFERENCE}" -> "${INDEXED_ARRAY[@]} -> the array elements, as we have seen before $ printf '%s\n' "${!ARRAY_REFERENCE}" > arr > super *dangerous* name! > hello
main() {   declare -a INDEXED_ARRAY=('arr' 'super *dangerous* name!' 'hello')
do_cool_stuff 'INDEXED_ARRAY[@]'
# $1 - array name
do_cool_stuff() { local array_name="$1"; shift
# get the array elements and stick them in a new array
declare -a MY_INDEXED_ARRAY=("${!array_name}")
printf '%s\n' "${MY_INDEXED_ARRAY[@]}"
> arr > super *dangerous* name! > hello



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloud 66

Cloud 66

DevOps-as-a-Service to help developers build, deploy and maintain apps on any Cloud. Sign-up for a free trial by visting: