bash: arrays - assignment, looping, and indexing
2008-11-16 Sun – 03:40:11## arrays in bash: assignment, indexing, and looping
##
# assign multiple values to a new array:
array=(tits arse)
# or:
array=([0]=tits [1]=arse)
# or:
array=([0]=tits arse)
# assign single values to specific indices:
array[2]='cheese'
# add a new value to the end of the array (push)
array+=(hmm)
# NB: indices do not have to be congiuous:
array[5]='last'
# view specific element of an array:
echo "first element: ${array[1]}"
echo "----"
# view number of elements in an array:
echo "${#array[*]} total elements"
echo "----"
# loop through an array by index:
for x in ${!array[*]}
do
echo "\${array[$x]} -> ${array[$x]}"
done
echo "----"
# loop through an array by value:
for y in ${array[*]}
do
echo $y
done
exit
## --
## output
## --
"test.sh" 67L, 1089C written
:!bash -D test.sh
:![ $? -eq 0 ] && test.sh
first element: arse
----
5 total elements
----
${array[0]} -> tits
${array[1]} -> arse
${array[2]} -> cheese
${array[3]} -> hmm
${array[5]} -> last
----
tits
arse
cheese
hmm
last