Dave Rau
Dave Rau

Reputation: 103

shell array loop stops after 1

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

Upvotes: 1

Views: 197

Answers (2)

sirgeorge
sirgeorge

Reputation: 6531

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

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

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").

Upvotes: 2

Related Questions