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。