國慶過后;感覺有點慵懶些了;接著上篇;我們繼續來學習循環語句。
一. for循環
與其他編程語言類似,Shell支持for循環。
for循環一般格式為:for 變量 in 列表do command1 command2 ... commandNdone
列表是一組值(數字、字符串等)組成的序列,每個值通過空格分隔。每循環一次,就將列表中的下一個值賦給變量
例如,順序輸出當前列表中的數字
for01.sh$ cat for01.sh #!/bin/shfor i in 1 2 3 4 5do echo "this is $i"done$ ./for01.sh this is 1this is 2this is 3this is 4this is 5
當然也可以向其他語言那樣for ((i=1;i++<5));但是是要雙括號;這個是與眾不同。
#!/bin/shfor ((i=1;i<=5;i++))do echo "this is $i"done
【注意】in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。如下:
$ cat for01.sh #!/bin/shfor ido echo "this is $i"done$ ./for01.sh 1 2 3 4 5 this is 1this is 2this is 3this is 4this is 5
【note】對于列表;像上面一樣;其實命令ls當前目錄下的所有文件就是一個列表
二.while 循環
while循環用于不斷執行一系列命令,也用于從輸入文件中讀取數據;命令通常為測試條件
#其格式為:while commanddo Statement(s) to be executed if command is truedone
命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。以for循環的例子。
$ cat while01.sh #!/bin/shi=0while [ $i -lt 5 ]do let "i++" echo "this is $i"done$ ./while01.sh this is 1this is 2this is 3this is 4this is 5
其實while循環用的最多是用來讀文件。
#!/bin/bashcount=1 cat test | while read line #cat 命令的輸出作為read命令的輸入,read讀到的值放在line中do echo "Line $count:$line" count=$[ $count + 1 ] done或者如下#!/bin/shcount=1whileread linedo echo "Line $count:$line" count=$[ $count + 1 ] done<test
【注意】當然你用awk的話;那是相當簡單;awk '{PRint "Line " NR " : " $0}' test輸出時要去除冒號域分隔符,可使用變量IFS。在改變它之前保存IFS的當前設置。然后在腳本執行完后恢復此設置。使用IFS可以將域分隔符改為冒號而不是空格或tab鍵
例如文件worker.txtLouiseConrad:Accounts:ACC8987PeterJamas:Payroll:PR489FredTerms:Customer:CUS012JamesLenod:Accounts:ACC887FrankPavely:Payroll:PR489while02.sh如下:#!/bin/sh#author:li0924#SAVEIFS=$IFSIFS=:whilereadnamedeptiddoecho-e"$name/t$dept/t$id"done<worker.txt#IFS=$SAVEIFS
三.until循環
until 循環執行一系列命令直至條件為 true 時停止。until 循環與 while 循環在處理方式上剛好相反
until 循環格式為: until commanddo Statement(s) to be executed until command is truedone
command 一般為條件表達式,如果返回值為 false,則繼續執行循環體內的語句,否則跳出循環
$ cat until01.sh #!/bin/shi=0until [ $i -gt 5 ]do let "i++" echo "this is $i"done
一般while循環優于until循環,但在某些時候,也只是極少數情況下,until 循環更加有用。詳細介紹until就不必要了
四. break和continue命令
1. break命令break命令允許跳出所有循環(終止執行后面的所有循環)2.continue命令continue命令與break命令類似,只有一點差別,它不會跳出所有循環,僅僅跳出當前循環。
break01.sh#!/bin/shfor ((i=1;i<=5;i++))do if [ $i == 2 ];then break else echo "this is $i" fidone
至于continue命令演示;你就把break替換下;執行看下效果就行了。不解釋。
新聞熱點
疑難解答