linux while和until循环项目案例

 项目脚本案例


1. 判断局域网主机存活脚本(主要吸取判断方法,利用until判断,避免多次使用if条件判断)

#!/bin/bash

   declare -i  i=0

   declare -i  j=1

    #++++++++++++++++++++利用until判断用户输入是否合法++++++++++++++++++++++++++++++++++++++

   until [[  $netid =~ ([0-9]{1,3}\.){3}[0-9]{1,3} ]];do  #如果满足条件则退出循环,否则进入循

          read -p "Input  network(eg:192.168.0.0): " netid

          let i++

          if [ $i -eq 3 ];then                            #如果3次错误输入,则退出脚本

                  echo "Input network times  out!"

                  exit 1

          fi

  done

  net=`echo  $netid|cut -d. -f1-3`

   #+++++++++++++++++++++++ping function++++++++++++++++++++++++++++++++++++++++++++++++++++

  Ping () {                                               #定义函数ping的主体

  while [ $j  -lt 255 ];do

          if ping -c1 -w1 $net.$j  &>/dev/null;then

                  echo "$net.$j is  up"

          else

                  echo "$net.$j is  down"

          fi

          let j++

  done

  }

  Ping                                                    #调用函数                  

2.利用while循环及调用系统本身function,每2s监控网站是否正常?

#!/bin/bash

  .  /etc/rc.d/init.d/functions                           #执行系统函数调用

#+++++++++++++++++++++arg  select+++++++++++++++++++++++++++++++++++++++++++++++++++++

if [ $# -ne 1 ];then

        echo  $"usage $0 url"

        exit 1

fi

#++++++++++++++++++++web  monitor+++++++++++++++++++++++++++++++++++++++++++++++++++++

flag=`curl -o /dev/null --connect-timeout 5 -s -w  "%{http_code}" $1|egrep -w "200|301|302"|wc -l`

run (){

while true;do

    if [ $flag  -ne 1 ];then

                action  "$1 is error." /bin/false    #调用系统函数action,其中fales时echo $? 假

        else

                action  "$1 is ok." /bin/true

    fi                                               #action函数再次调用一系列函数组成ok和fail

sleep 2

done

}

run "$1"

[root@centos7 ~/test]#./curl.sh http://www.baidu.com
http://www.baidu.com is ok.                                [  OK  ]
http://www.baidu.com is ok.                                [  OK  ]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章