shell基礎(八)-循環語句

   國慶事後;感受有點慵懶些了;接着上篇;咱們繼續來學習循環語句。python

    一. for循環編程

        與其餘編程語言相似,Shell支持for循環。bash

for循環通常格式爲:
for 變量 in 列表
do
    command1
    command2
    ...
    commandN
done

   列表是一組值(數字、字符串等)組成的序列,每一個值經過空格分隔。每循環一次,就將列表中的下一個值賦給變量編程語言

   例如,順序輸出當前列表中的數字學習

for01.sh
$ cat for01.sh 
#!/bin/sh
for i in 1 2 3 4 5
do
 echo "this is $i"
done
$ ./for01.sh 
this is 1
this is 2
this is 3
this is 4
this is 5

 固然也能夠向其餘語言那樣for ((i=1;i++<5));可是是要雙括號;這個是不同凡響。測試

#!/bin/sh
for ((i=1;i<=5;i++))
do
 echo "this is $i"
done

 【注意】in 列表是可選的,若是不用它,for 循環使用命令行的位置參數。以下:ui

$ cat for01.sh 
#!/bin/sh
for i
do
 echo "this is $i"
done
$ ./for01.sh 1 2 3 4 5  
this is 1
this is 2
this is 3
this is 4
this is 5

 【note】對於列表;像上面同樣;其實命令ls當前目錄下的全部文件就是一個列表this


 

   二.while 循環命令行

while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令一般爲測試條件blog

#其格式爲:
while command
do
   Statement(s) to be executed if command is true
done

 命令執行完畢,控制返回循環頂部,從頭開始直至測試條件爲假。
以for循環的例子。

$ cat while01.sh 
#!/bin/sh
i=0
while [ $i -lt 5 ]
do
 let "i++"
 echo "this is $i"
done
$ ./while01.sh 
this is 1
this is 2
this is 3
this is 4
this is 5

 其實while循環用的最可能是用來讀文件。

#!/bin/bash
count=1    
cat test | while read line        #cat 命令的輸出做爲read命令的輸入,read讀到的值放在line中
do
   echo "Line $count:$line"
   count=$[ $count + 1 ]          
done
或者以下
#!/bin/sh
count=1
while read line
do 
  echo "Line $count:$line"
   count=$[ $count + 1 ]  
done < test

 【注意】固然你用awk的話;那是至關簡單;awk '{print "Line " NR " : " $0}' test
輸出時要去除冒號域分隔符,可以使用變量IFS。在改變它以前保存IFS的當前設置。而後在腳本執行完後恢復此設置。使用IFS能夠將域分隔符改成冒號而不是空格或tab鍵

例如文件worker.txt
Louise Conrad:Accounts:ACC8987
Peter Jamas:Payroll:PR489
Fred Terms:Customer:CUS012
James Lenod:Accounts:ACC887
Frank Pavely:Payroll:PR489
while02.sh以下:
#!/bin/sh
#author: li0924
#SAVEIFS=$IFS
IFS=:
while read name dept id
 do
  echo -e "$name\t$dept\t$id"
 done < worker.txt
#IFS=$SAVEIFS

 

   三.until循環

until 循環執行一系列命令直至條件爲 true 時中止。until 循環與 while 循環在處理方式上恰好相反

until 循環格式爲: 
until command
do
   Statement(s) to be executed until command is true
done

 command 通常爲條件表達式,若是返回值爲 false,則繼續執行循環體內的語句,不然跳出循環

$ cat until01.sh 
#!/bin/sh
i=0
until [ $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/sh
for ((i=1;i<=5;i++))
do
 if [ $i == 2 ];then
 break
 else
 echo "this is $i"
 fi
done

 至於continue命令演示;你就把break替換下;執行看下效果就好了。不解釋。

相關文章
相關標籤/搜索