標籤: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