views:

1286

answers:

6

How can I iterate through a simple range of ints using a for loop in ksh?

For example, my script currently does this...

for i in 1 2 3 4 5 6 7
do
   #stuff
done

...but I'd like to extend the range way above 7. Is there a better syntax?

Thanks!

+2  A: 

While loop?

while [[ $i -lt 1000 ]] ; do
    # stuff
   (( i += 1 ))
done
Lance Rushing
Thanks - that'd do nicely, but is there no other for loop syntax?
sgreeve
+1 for the alternative suggestion
sgreeve
+4  A: 

Curly brackets?

for i in {1..7}
do
   #stuff
done
martin clayton
Bingo - thanks!
sgreeve
See also http://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-in-bash
martin clayton
+3  A: 

ksh, Bash and zsh all understand C-like for loop syntax:

for ((i=1; i<=9; i++))
do
    echo $i
done

Unfortunately, while ksh and zsh understand the curly brace range syntax with constants and variables, Bash only handles constants (including Bash 4).

Dennis Williamson
Thanks - +1 for not only providing a useful answer, but for doing so even though I'd already accepted an earlier answer.
sgreeve
+1  A: 

seq - but only available on linux.

for i in `seq 1 10`
do 
    echo $i
done

there are other options for seq. But the other solutions are very nice and more important, portable. Thx

cheko
+2  A: 

Curly brackets {1..7} don´t work in ksh. They do in Linux, because linux's ksh is a symlink to bash shell.

Also c-like sintax doesn´t work in the proper korn shell neither.

Perkolator
A: 

on OpenBSD, use jot:

for i in `jot 10`; do echo $i ; done;
Colin