Showing results for 
Search instead for 
Do you mean 

for loop question

SOLVED
Go to Solution
Advisor

for loop question

Hi there

I have 3 values, each comprising 3 elements.
On the command line:

for i in '1 2 3' '4 5 6' '7 8 9' etc works

but in a script all hell breaks loose.

can anyone assist pls ?

I would like to run this within a script but Ive tried "'1 2 3' '4 5 6' '7 8 9' " and ''1 2 3' '4 5 6' '7 8 9' ' ...and both dont work.

Thks in advance
1 ACCEPTED SOLUTIONS
Acclaimed Contributor Acclaimed Contributor

Re: for loop question

Hi (again):

Do you mean this?

#!/bin/sh
list1="123"
list2="456"
list3="789"
elements="${list1} ${list2} ${list3}"
for i in ${elements}
do
echo ${i}
done

Regards!

...JRF...
7 REPLIES
Advisor

Re: for loop question

sorry ...I forgot to add that within a script it DOES work but I would like to create a variable ..so

elements="'123' '456' '789'"

and then do

for i in $elements ....

this is the bit that goes wrong.
Id like to setup a var in case I have a huge number of elements - thks and sorry for the confusion
Acclaimed Contributor Acclaimed Contributor

Re: for loop question

Hi:

> but in a script all hell breaks loose.

That's a useless description. Show us the script (or better an example case with code) and describe what you want to do and what does happen.

Regards!

...JRF...
Acclaimed Contributor Acclaimed Contributor

Re: for loop question

Hi (again):

Do you mean this?

#!/bin/sh
list1="123"
list2="456"
list3="789"
elements="${list1} ${list2} ${list3}"
for i in ${elements}
do
echo ${i}
done

Regards!

...JRF...
Acclaimed Contributor Acclaimed Contributor

Re: for loop question

>I have a huge number of elements

You could create an array if there aren't more than 1023 elements:
set -A elements '123' '456' '789'

>for i in $elements ....

Replace by:
for i in "${elements[@]}"; do

Honored Contributor Honored Contributor

Re: for loop question

> but in a script all hell breaks loose.

> this is the bit that goes wrong.

Have you considered the possible advantages
of explaining what you're actually doing, and
what actually goes wrong when you do it?
Advisor

Re: for loop question

lol ... ahh nothing like getting on the band wagon for a good old tar and feathering. I guess Ill just have to be more explicit next time...but fab answers.

Ok so "all hell breaks loose" was at tabd melodramatic. The new chastized me now says:

My previous efforts hitherto produced an array of results ranging from $i being equal to each entry in the group of elements or $i being equal to the entire string. These observations were when I assigned the groups to an array, albeit , incorrectly.

I see from the above how to correctly assign grouped elements to a variable to be used in the for loop.

Thks for all your comments and help.
Advisor

Re: for loop question

thks to all