• 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 "33[32m $net$i is alive 33[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

  • 相关阅读:
    Python基础 面向对象的基本概念
    C#版菜谱
    Ember源码学习
    AutoFac文档
    NewLife.Xcode组件资源目录
    Go语言
    调试Razor从哪里开始
    搭建一个高并发低时延系统
    ASP.NET MVC以ModelValidator为核心的Model验证体系: ModelValidatorProvider
    2012百度之星资格赛试题与AC代码合集
  • 原文地址:https://www.cnblogs.com/sunny18/p/8618445.html
Copyright © 2020-2023  润新知