日期:2014-05-16  浏览次数:20753 次

UNIX Shell循环控制—while

while循环,语法如下:

while command
do
  Statement(s) to be executed if command is true
done

command可以是一个判断,也可以是一个命令,如读取文件等。

当command条件为真,则执行循环中的语句块,否则直接退出循环。


实例1、简单的while循环

打印从0到10的数据:

pg while1.sh
#!/bin/ksh
i=0
while [ $i -le 10 ]
do
  echo $i
  i=`expr $i + 1`
done
#EOF

执行脚本:

sh while1.sh
0
1
2
3
4
5
6
7
8
9
10

实例2、我想将当前目录下文件名包含if的文件全部移动到iftest文件夹下面。

这里借助于一个临时文件temp.txt,创建之后,保存从当前文件夹下中查询到的文件;

用完之后,将其删除。

pg mvfile.sh
#!/bin/ksh
echo "moving all file which contain word if to directory iftest"

# create temporary file temp.txt
if [ -f temp.txt ]; then
  ""  > temp.txt
  echo "clearing temp.txt file successful"
else
  touch  temp.txt
  echo "making file temp.txt successfull"
fi

# writing file temp.txt with file contain word if
ls -l | grep '^-.*' | sed -n '/if/'p | awk '{print $9}' > temp.txt

# moving file to directory iftest
while read LINE
do
  mv $LINE ./iftest
done < temp.txt

# droping the temporary file after moving
echo "moving file with if successfull"
if  rm -f temp.txt > /dev/null  2>&1; then
  echo "removing file temp.txt successful"
fi
#EOF

执行此脚本之前,当前目录下文件如下:

.../shell>lf
calculator.sh      ifcp2.sh           ifroot.sh          param.sh
child.sh*          ifdirec.sh         ifset.sh           profile.sh
data.file          ifeditor.sh        iftest/            test/
elif.sh            ifelif.sh          iftest2.sh         testdirec/
env_variable       ifels.sh           iftst.sh*          test1/
father.sh*         ifinteractive.sh   ifwr.sh            tst/
grepif.sh          ifmkdir.sh         if1.sh*            welcome.sh
grepstr.sh         ifmkdir2.sh        if2.sh             125017.sh
ifcounter.sh       ifparam.sh         log.txt
ifcp.sh            ifpwd.sh           name.txt

执行之后,包含if的文件全部被移动到iftest目录下:

.../shell/iftest>lf
elif.sh            ifeditor.sh        ifparam.sh         ifwr.sh
grepif.sh          ifelif.sh          ifpwd.sh           if1.sh*
ifcounter.sh       ifels.sh           ifroot.sh          if2.sh
ifcp.sh            ifinteractive.sh   ifset.sh
ifcp2.sh           ifmkdir.sh         iftest2.sh
ifdirec.sh         ifmkdir2.sh        iftst.sh*
--the end--