views:

729

answers:

4

I want to write a loop in bourne shell which iterates a specific set of numbers. Normally I would use seq

for i in `seq 1 10 15 20`
   #do stuff
loop

But seemingly on this Solaris box seq does not exist. Can anyone help by providing another solution to iterating a list of numbers?

Thanks, Chris

+3  A: 

try

for i in 1 10 15 20
do
   echo "do something with $i"
done

else if you have recent Solaris, there is bash 3 at least. for example this give range from 1 to 10 and 15 to 20

for i in {1..10} {15..20}
do
  echo "$i"
done

OR use tool like nawk

for i in `nawk 'BEGIN{ for(i=1;i<=10;i++) print i}'`
do
  echo $i
done

OR even the while loop

while [ "$s" -lt 10 ]; do s=`echo $s+1|bc`; echo $s; done
ghostdog74
Thanks Ghost, not sure why I didn't try that right off!
Chris Kannon
You might want to use `expr $s + 1` instead of `echo $s+1|bc`. The `expr` utility is meant for this sort of thing. Of course with `ksh` or `bash` you can just use shell arithmetic.
D.Shawley
and so is bc. not to mention bc does a lot more than expr. thks for the reminder anyway.
ghostdog74
Why do people prefer the ambiguity of bc to the precision of dc? Am I really that old?
William Pursell
define ambiguity.
ghostdog74
A: 

I find that this works, albeit ugly as sin:

for i in `echo X \n Y \n Z ` ...
cyborg
+1  A: 

You can emulate seq with dc:

For instance:

seq 0 5 120

is rewritten as:

dc -e '0 5 120  1+stsisb[pli+dlt>a]salblax'
mouviciel
+1 for creativity,this-> nawk 'BEGIN{ for(i=0;i<=120;i+=5 )print i }' does the same and more readable
ghostdog74
I tried to use basic tools, since OP mentions bourne shell. But I didn't think of `awk`.
mouviciel
+1  A: 

Another variation using bc:

for i in $(echo "for (i=0;i<=3;i++) i"|bc); do echo "$i"; done

For the Bourne shell, you'll probably have to use backticks, but avoid them if you can:

for i in `echo "for (i=0;i<=3;i++) i"|bc`; do echo "$i"; done
Dennis Williamson