shell迴圈loop

來源:互聯網
上載者:User

標籤:shell   loop   while   until   for   

1. 迴圈
shell迴圈,不斷執行某段程式,直到符合條件。迴圈分為4種, while迴圈,until迴圈,for固定處理, for數值處理。
2. while迴圈
while迴圈是一直執行,直到條件不符合,才停止。文法:while [ condition ]do//do somethingdone例: 迴圈直到使用者輸入正確
#!/bin/bash# desc : while loopwhile [ "$yn" != "yes" -a "$yn" != "YES" ] do     read -p "Please input yes/YES to stop : " yndoneecho "OK"
執行結果:
[[email protected] sh]$ sh while.sh Please input yes/YES to stop : noPlease input yes/YES to stop : yesOK[[email protected] sh]$ 
例:從1加到100
#!/bin/bash# desc : while loopsum=0i=0while [ $i -lt 100 ]do    i=$(($i+1));    sum=$(($sum+$i))doneecho "From 1 to 100, sum is : " $sum 
3. until迴圈
until迴圈和while相反,當條件condition成立時,終止迴圈。文法:until [ condition ]do//do somethingdone例:
#!/bin/bash# desc : while loopuntil [ "$yn" == "yes" -o "$yn" == "YES" ]do    read -p "Please input yes/YES to stop : " yndoneecho "OK"
執行:
[[email protected] sh]$ sh while.sh Please input yes/YES to stop : hi         Please input yes/YES to stop : yesOK[[email protected] sh]$ 

4. for固定迴圈
for為已知次數的迴圈。文法:for var in con1 con2 ..do//do somethingdone例:
#!/bin/bash# desc : for loopfor animal in dog cat pig do    echo "HI, ${animal}"done
執行:
[[email protected] sh]$ sh for.sh HI, dogHI, catHI, pig[[email protected] sh]$
例:目前的目錄檔案
#!/bin/bash# desc : for loopfilelist=$(ls)for filename in $filelistdo    echo $filenamedone

5. for數值迴圈
for數值迴圈,適用於迴圈數值計算。文法for (( 初始值; 限制值; 步長))do// do somethingdone例:
#!/bin/bash# desc : for loopsum=0for (( i=0; i<=100; i++ ))do    sum=$(($sum+$i))doneecho "sum is : " $sum

地址:http://blog.csdn.net/yonggang7/article/details/40679701

shell迴圈loop

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.