shell array loop stops after 1

Go To StackoverFlow.com

0

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
2012-04-03 22:02
by Dave Rau
/bin/sh does not support arrays. Change your shebang to "#!/bin/bash" if you intend your script to be running under bash - William Pursell 2012-04-03 22:09


2

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

2012-04-03 22:06
by Andrew Clark
Thanks FJ. I'm curious what's the difference between using [@] and [*] - Dave Rau 2012-04-03 22:36
@RedLabor Without quotes there is no difference, [*] 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
@RedLabor, this is particularly important if any of the colors has a space, such as colors[7]="light blue" -- then "${colors[@]}" is the only way to properly iterate - glenn jackman 2012-04-04 13:14


2

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
2012-04-03 22:09
by sirgeorge
Ads