国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 操作系統 > 正文

shell基礎(八)-循環語句

2024-06-28 13:23:48
字體:
來源:轉載
供稿:網友
shell基礎(八)-循環語句

國慶過后;感覺有點慵懶些了;接著上篇;我們繼續來學習循環語句。

一. 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替換下;執行看下效果就行了。不解釋。


上一篇:libevent入門(1)

下一篇:操作系統

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 时尚| 临桂县| 西昌市| 介休市| 平陆县| 盐源县| 商洛市| 玛纳斯县| 天台县| 邹城市| 湘阴县| 桂东县| 舒兰市| 修武县| 龙陵县| 罗江县| 阿拉善右旗| 镇宁| 江达县| 来凤县| 章丘市| 永仁县| 醴陵市| 茂名市| 界首市| 栾川县| 灵山县| 宜兴市| 综艺| 金昌市| 汝南县| 赣州市| 六枝特区| 长岛县| 宾阳县| 若尔盖县| 右玉县| 满洲里市| 武强县| 车险| 安顺市|