1. 程式人生 > >linux while和until循環項目案例

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"

[[email protected] ~/test]#./curl.sh http://www.baidu.com
http://www.baidu.com is ok. [ OK ]
http://www.baidu.com is ok. [ OK ]


本文出自 “11831715” 博客,請務必保留此出處http://11841715.blog.51cto.com/11831715/1960244

linux while和until循環項目案例