你好,游客 登录 注册 搜索
背景:
阅读新闻

UNIX Shell循环控制—while

[日期:2013-02-02] 来源:Linux社区  作者:bobo12082119 [字体:大 中 小]

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--

linux
相关资讯       Unix shell  Shell while循环 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款