How to use loop statements in unix shell scripting for eg whi开发者_如何学Pythonle ,for do while. I'm using putty server.
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/
#!/bin/sh
items=(item1 item2 item3)
len=${#items[*]}
i=0
while [ $i -lt $len ]; do
echo ${items[$i]}
let i++
done
exit 0
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.
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
using for loop
max=10
for (( i=0; i<=$max; i++ ));
do
echo $i
done
to iterate through a file in KSH
while read line ; do
echo "line from file $line"
done < filename.txt
echo "sample while loop"
i=0;
while [ $i -le 10 ]
do
echo $i
(( i++ ))
done
精彩评论