Bash array
Getting started
myarr=() #Make an empty array
myarr=(a b c 3 2 1) #Initialize an array
${myarr[4]} #Getting 5th element
${myarr[@]} #Getting all emements
${!myarr[@]} #Getting indices
${#myarr[@]} #Getting length
myarr[2]=3 #Modify 3nd element
myarr+=(x y z) #Append elements
myarr=( $(ls) ) #Save `ls` out as an array
${myarr[@]:s:n} #Retrieve n elements beginning at index s
unset myarr[0] #Destroy 1st element
unset myarr #Remove the entire array
Looping array elements
${myarr[@]}
stands to all members of the array myarr
,so you can use for
command to loop array elements
$myarr=(a b c 3 2 1)
$for x in ${myarr[@]}; do echo $x; done
a
b
c
3
2
1
Looping array indices
${!myarr[@]}
stands the index of array myarr
, starts at zero .
$myarr=(a b c 3 2 1)
$for i in ${!myarr[@]}; do echo "indice $i = ${myarr[i]}"; done
indice 0 = a
indice 1 = b
indice 2 = c
indice 3 = 3
indice 4 = 2
indice 5 = 1
$* vs $@
For array both @
and *
expands all the elements of an array ,but they differ only when the word appears within double quotes.${arr[*]}
expands to a single word with the value of each array member by IFS
(space by default), and ${name[@]}
expands each element of name to a separate word.
$arr=(1 "Hello world" 2)
$for x in "${arr[*]}"; do echo $x; done
1 Hello world 2
$for x in "${arr[@]}"; do echo $x; done
1
Hello world
2
$
- Note the
Hello world
been quoted.
Associative array (dictionary)
declare -A dict #Declare an associative arry
declare -A dict=( [key1] value1 [key2] value2 )
dict['key3']='value3' #Add or modify element
${dict[@]} #expand the values
${!animals[@]} #expand the keys
For example:
$declare -A dict=( [key1]=value1 [key2]=value2 )
$echo ${dict[key2]}
value2
$echo ${dict[@]}
value2 value1
$echo ${!dict[@]}
key2 key1