设为首页 加入收藏

TOP

UNIX Shell循环控制—while
2014-11-24 08:27:22 来源: 作者: 【 】 浏览:0
Tags: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--


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇第一个Unix Shell函数 下一篇Unix Shell控制结构—CASE

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python 数据分析与可 (2025-12-26 21:51:20)
·从零开始学Python之 (2025-12-26 21:51:17)
·超长干货:Python实 (2025-12-26 21:51:14)
·为什么 Java 社区至 (2025-12-26 21:19:10)
·Java多线程阻塞队列 (2025-12-26 21:19:07)