for cycle

Hello,

I have a question:
is there a way to have a "for" cycle done a certain number of times. For example in c++ I can do this:
for (i=o;i<10;i++)
and the cycle will be repeated 10 times.
in UNIX for example I do this:
for i in `cat /etc/host` do done
and the cycle will be repeated depending the item in the file
can something similar be done on UNIX?

thanks

yes. depending on the scripting language you're using....

in ksh:

num=0

while [ $num -lt 10 ]; do

  num=$(( num + 1 ))

  echo doing something...

done

not very elegant...

in csh:

repeat 10 echo something

in perl:


for ( 0 .. 9 ){
  print "doing something\n";
  }

HTH

x=1
while [[ $x -lt 10 ]] 
do
     x=$(( $x + 1 ))
done

The for () construct doesn't exist in POSIX shells, just the (shudder) c shell.

are you sure?

cjajohnson corrected my use of the idiom:

(( x = x + 1 ))

... saying it wasn't POSIX compliant -- and offered the x=$$(( x + a ))
instead.

I think I'll just give my answers in ksh unless the poster complains
from now on.

Try it - it is correct

output with set -x

 t.sh
+ x=1
+ [[ 1 -lt 10 ]]
+ x=2
+ [[ 2 -lt 10 ]]
+ x=3
+ [[ 3 -lt 10 ]]
+ x=4
+ [[ 4 -lt 10 ]]
+ x=5
+ [[ 5 -lt 10 ]]
+ x=6
+ [[ 6 -lt 10 ]]
+ x=7
+ [[ 7 -lt 10 ]]
+ x=8
+ [[ 8 -lt 10 ]]
+ x=9
+ [[ 9 -lt 10 ]]
+ x=10
+ [[ 10 -lt 10 ]]
#!/bin/ksh

set -x
x=1
while [[ $x -lt 10 ]] 
do
     x=$(( $x + 1 ))
done

thank so much guys!!!

ksh, bash, zsh all accept:

for ((i=0; i < 10; i++)) 
do 
  echo $i;
done