shell script 之五:循環控制 for


for循環

基本語法:

for var in item1 item2 ... itemN do command1 command2 ... commandN done

 

例1:計算1到100數字的和

#!/bin/sh
#the sum  1-100

sum=0
for ((i=1;i<=100;i++));
do
  let sum=$sum+$i;  #可以寫 sum=$(( $sum + $i )) 
done
  echo $sum

sh sum100.sh 
5050

  

例2:獲取網段內在線主機ip,並保存到ip.txt

#!/bin/bash
#find alive_ip >ip.txt
#by sunny 2013

net="10.0.0."  #定義網段
for ((i=1;i<=254;i++))
do
  ping -c1 $net$i >/dev/null 2>&1  #-c指定次數,結果不輸出
  if [ $? -eq 0 ];then
    echo -e "\033[32m $net$i is alive \033[0m"
    echo "$net$i  is  ok" >>ip.txt
  else
    echo "net$i is none"
  fi
done

 

運行sh getaliveip.sh 

~ sh getaliveip.sh
10.0.0.1 is alive
10.0.0.2 is none
10.0.0.3 is none
10.0.0.4 is none
10.0.0.5 is none
10.0.0.6 is none
10.0.0.7 is none
10.0.0.8 is alive
10.0.0.9 is none
10.0.0.10 is none

 

 例3:可以直接利用反引號` `  或者$()給變量賦值。 

for i in `seq -f"%03g" 5 8`;   # "%03g" 指定seq輸出格式,3標識位數,0標識用0填充不足部分
do echo $i;  

done   
005
006
007
008

 使用$(),列出/etc下rc開頭的文件

for i in $(ls /etc/);do echo $i|grep ^rc; done

  

例4:for in {v1,v2,v3}

for i in {0..3};do echo $i; done
0
1
2
3

for i in v1 v2 v3;do echo $i; done
v1
v2
v3

 

例5:利用seq生成一些網頁批量下載

for i in `seq 1 4`;  do wget -c "http://nginx.org/download/nginx-1.10.$i.zip";  done

也可以先用seq生成網頁

for i in `seq -f "http://nginx.org/download/nginx-1.10.%g.zip"  1 4`; do wget -c $i; done
 以上同
for i in $(seq -f "http://nginx.org/download/nginx-1.10.%g.zip"  1 4); do wget -c $i; done

  

 

 

終止循環:break主要用於特定情況下跳出循環,防止死循環。while循環也一樣。

#!/bin/bash
#by sunny

for((i=10;i<100;i++))
do
  if [ $i -gt 15 ];then  # i 大於15退出循環
    break
  fi
  echo "the sum is $i"
done

# sh break.sh
the sum is 10
the sum is 11
the sum is 12
the sum is 13
the sum is 14
the sum is 15

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM