shell迴圈loop,shellloop

來源:互聯網
上載者:User

shell迴圈loop,shellloop
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"
執行結果:
[work@www sh]$ sh while.sh Please input yes/YES to stop : noPlease input yes/YES to stop : yesOK[work@www 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"
執行:
[work@www sh]$ sh while.sh Please input yes/YES to stop : hi         Please input yes/YES to stop : yesOK[work@www 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
執行:
[work@www sh]$ sh for.sh HI, dogHI, catHI, pig[work@www 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中的for 迴圈,為何老出錯,我實在看不出來哪錯了

#!/bin/sh
x=1
y=2
for ((i=1;i<$1;i++))
do
m=$y
let y=$x+$y
x=$m
done
echo $x/$y
 
shell中的for為何兩個括弧

for loop 的文法有下列兩種:

(1)這個是shell的古典for的用法:
for varname [in word...]
do
...
done

舉例:
for i in a b c
do
echo $i
done

(2) 這個文法類似C/C++的用法,還有((...))在shell裡是算數運算用:

for (( [init_expression];[loop_condition];[loop_expression] ))
do
...
done

舉例:
for ((i=0;i<5;i++))
do
echo $i
done

注意事項:這個for的用法只有在1988-11-16後的ksh才支援,所以有許多的Unix還不支援這個for的使用文法。例如HPUX或IBM的AIX。
 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.