views:

284

answers:

5

How to use loop statements in unix shell scripting for eg while ,for do while. I'm using putty server.

A: 

for: Iterate over a list.

$for i in `cat some_file | grep pattern`;do echo $i;done

while loop looks pretty much like C's.

$ i=0;while [ $i -le 10 ];do echo $i;i=`expr $i + 1` ;done

If you are going to use command line only, you could use perl, but I guess this is cheating.

$perl -e '$i=0;while ($i < 10){print $i;$i++;}'

More data

http://www.freeos.com/guides/lsst/

Tom
first one is bad example of a useless use of ls. for i in *;do echo $i;done
second example: i=`expr $i+1` <--- no need to call external expr. $((i+1)) or $((i++))
I've change the ls for something else. Its just an example to show the for loop structure.
Tom
+1  A: 
#!/bin/sh
items=(item1 item2 item3)

len=${#items[*]}

i=0
while [ $i -lt $len ]; do
  echo ${items[$i]}
  let i++
done

exit 0
mesut
Strictly, that requires bash rather than a Bourne shell; on many modern systems, there is no Bourne shell and /bin/sh is a link to /bin/bash.
Jonathan Leffler
A: 

As well as the 'for' and 'while' loops mentioned by Tom, there is (in classic Bourne and Korn shells at least, but also in Bash on MacOS X and presumably elsewhere too) an 'until' loop:

until [ -f /tmp/sentry.file ]
do
    sleep 3
done

This loop terminates when the tested command succeeds, in contrast to the 'while' loop which terminates when the tested command fails.

Also note that you can test a sequence of commands; the last command is the one that counts:

while x=$(ls); [ -n "$x" ]
do
    echo $x
done

This continues to echo all the files in the directory until they're all deleted.

Jonathan Leffler
A: 

to the OP, to iterate over files

for file in *
do
 echo "$file"
done

to generate counters

for c in {0..10}
do
 echo $c
done
A: 

to iterate through a file in KSH

while read line ; do

echo "line from file $line"

done < filename.txt

Venkataramesh Kommoju