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

 

posted @ 2018-03-22 11:36  sunny18  阅读(2023)  评论(0编辑  收藏  举报