shell script 之五:循環控制 for

for循環

基本語法:nginx

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

 

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

#!/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.txtspa

#!/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 blog

~ 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 noneip

 

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

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

done   
005
006
007
008

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

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

  

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

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生成一些網頁批量下載class

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 10the sum is 11the sum is 12the sum is 13the sum is 14the sum is 15

相關文章
相關標籤/搜索