I'm at a loss why this loop stops after the first item. Can someone point me in a direction? Thanks!
#! /bin/sh
colors[0]="teal"
colors[1]="purple"
colors[2]="pink"
colors[3]="red"
colors[4]="green"
colors[5]="darkblue"
colors[6]="skyblue"
for color in ${colors}
do
echo $color
done
Try changing it to the following:
for color in "${colors[@]}"
do
echo $color
done
Removing the quotes would work for your example, but not if there were any spaces in a single color (for example "sky blue"
).
[*]
with quotes will give you the entire array on a separate line, [@]
with quotes will still give you each color on a separate line - Andrew Clark 2012-04-03 23:43
colors[7]="light blue"
-- then "${colors[@]}"
is the only way to properly iterate - glenn jackman 2012-04-04 13:14
One of the many ways to do it is to use for
loop. Additional info here is how to get the size of the array.
#Get the size of the array
nColors=${#colors[*]}
for (( Idx = 0; Idx < $nColors; ++Idx )); do
echo "${colors[$Idx]}"
done