歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> UNIX Shell循環控制—while

UNIX Shell循環控制—while

日期:2017/3/1 10:02:12   编辑:SHELL編程

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

Copyright © Linux教程網 All Rights Reserved