shell基礎(chǔ)(五)for循環(huán)及循環(huán)終止命令

一拥知、循環(huán)終止的特殊命令

break踏拜、exit、continue低剔、return的區(qū)別

break n:如果省略n速梗,則表示跳出整個循環(huán)、n表示跳出循環(huán)的層數(shù)
continue n:如果省略n襟齿,則表示跳出本次循環(huán)姻锁,忽略本次循環(huán)的剩余代碼,進入循環(huán)的下一個循環(huán)猜欺。n表示退到第n層繼續(xù)循環(huán)
exit n:退出當前shell位隶,n為上一次程序執(zhí)行的狀態(tài)返回值,n也可以省略开皿,在下一個shell里可通過"$?"接收exit n 的n值
return n :用于在函數(shù)里作為函數(shù)值返回涧黄,以判斷函數(shù)執(zhí)行是否正確,在下一個shell里可通過"$?"接收exit n 的n值

例一:

#!/bin/bash
if [ $# -ne 1 ];then
        echo $"usage:$0 {break|continue|exit|return}" 
        exit 1
fi
function test(){
        for ((i=0;i<5;i++))
        do
                if [ $i -eq 3 ];then
                        $*;
                fi
        done
        echo "I am in func"
}
test $*
func_ret=$?
if [ $(echo $*|grep return | wc -l) -eq 1 ];then
        echo "return's exit status:$func_ret"
fi
echo "ok"

效果如圖:

[root@mycentos shell]# sh 2.sh break
0
1
2
I am in func  #跳出for循環(huán)赋荆,后繼續(xù)執(zhí)行函數(shù)后面的代碼
ok        #執(zhí)行腳本后面的代碼

[root@mycentos shell]# sh 2.sh continue
0
1
2
4
I am in func   #將跳出for循環(huán)中本次循環(huán)笋妥,繼續(xù)執(zhí)行下次循環(huán)
ok             #腳本后面的內(nèi)容繼續(xù)執(zhí)行

[root@mycentos shell]# sh 2.sh "exit 119"
0
1
2  #直接跳出腳本,函數(shù)和腳本后面的內(nèi)容不執(zhí)行
[root@mycentos shell]# echo $?
119     退出程序時指定了"119",則執(zhí)行腳本后獲取"$?"的返回值就返回了"119",給當前的shell

[root@mycentos shell]# sh 2.sh "return  119"
0
1
2   #return 直接退出當前函數(shù)
return's exit status:119  #將119返回到了函數(shù)的外部腳本
ok
[root@mycentos shell]# echo $? 
0            #執(zhí)行腳本后的返回值為0窄潭,因為腳本中最后一條命令"ok"打印成功

實戰(zhàn)一:

開發(fā)shell腳本實現(xiàn)服務(wù)器臨時配置多個IP春宣,并且可以隨時撤銷配置的所有IP.IP的地址范圍為:10.0.2.1~10.0.2.16,其中10.0.2.10不能配置

預備知識:
一嫉你、給網(wǎng)卡配置額外IP的兩種方式
1.)ifconfig配置別名IP的方式
ifconfig eth0:0 10.0.2.10/24 up #添加IP
ifconfig eth0:0 10.0.2.10/24 down #刪除IP
2.)使用ip配置輔助IP的方式:
ip addr add 10.0.2.11/24 dev eth0 label eth0:0 #添加ip
ip addr del 10.0.2.11/24 dev eth0 label eth0:0 #刪除ip

簡略版:
#!/bin/bash
for num in $(seq 16)
do
        if [ $num -eq 10 ];then
                continue
        else
                #ip addr add  10.0.2.$num/24 dev eth0 label eth0:$num  <==這個也可以
                ifconfig eth0:$num 10.0.2.$num/24 down
        fi
done
簡單版本:
#!/bin/bash
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions
RETVAL=0
function add(){
        for ip in {1..16}
        do
                if [ $ip -eq 10 ];then
                        continue
                else
                        ifconfig eth0:$ip 10.0.2.${ip}/24 up
                        RETVAL=$?
                        if [ $RETVAL -eq 0 ];then
                                action "add $ip" /bin/true
                        else
                                action "add $ip" /bin/false
                        fi
                fi
        done
        return $RETVAL
}
function del(){
        for ip in {1..16}
        do
                if [ $ip -eq 10 ];then
                        continue
                else
                        ifconfig eth0:$ip 10.0.2.${ip}/24 down
                        RETVAL=$?
                        if [ $RETVAL -eq 0 ];then
                                action "del $ip" /bin/true
                        else
                                action "del $ip" /bin/false
                        fi
                fi 
        done
        return $RETVAL
}
case "$1" in
        start)
                add
                RETVAL=$?
                ;;
        stop)
                del
                RETVAL=$?
                ;;
        restart)
                del
                sleep 2
                add
                RETVAL=$?
                ;;
        *)
                printf $"usage:$0 {start|stop|restart}"
esac
exit $RETVAL
注:
    一信认、此版本代碼冗余多,可以將冗余代碼組合
去除代碼冗余版:
#!/bin/bash
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions
RETVAL=0
function op(){
        if [ "$1" == "del" ];then   #空格不要忘了
                list=$(echo {16..1})#從后往前刪除
        else
                list=$(echo {1..16})
        fi
        for ip in $list
         do
                if [ $ip -eq 10 ];then
                        continue   #跳出此次循環(huán)
                else
                        ip addr $1 10.0.2.$ip/24 dev eth0 label eth0:$ip &>/dev/null
                        RETVAL=$?
                        if [ $RETVAL -eq 0 ];then
                                action "$1 $ip" /bin/true
                        else
                                action "$1 $ip" /bin/false
                        fi
                fi
         done
        return $RETVAL
}
case "$1" in
        start)
                op add  #注意傳參到op函數(shù)中去
                RETVAL=$?
                ;;
        stop)
                op del
                RETVAL=$?
                ;;
        restart)
                op del
                sleep 2
                op add
                RETVAL=$?
                ;;
        *)
                printf $"usage:$0 {start|stop|restart}"
esac
exit $RETVAL

效果如下:

[root@mycentos ~]# sh 1.sh start
add 1                                                      [  OK  ]
add 2                                                      [  OK  ]
add 3                                                      [  OK  ]
add 4                                                      [  OK  ]
add 5                                                      [  OK  ]
add 6                                                      [  OK  ]
add 7                                                      [  OK  ]
add 8                                                      [  OK  ]
add 9                                                      [  OK  ]
add 11                                                     [  OK  ]
add 12                                                     [  OK  ]
add 13                                                     [  OK  ]
add 14                                                     [  OK  ]
add 15                                                     [  OK  ]
add 16                                                     [  OK  ]
使用ifconfig可查看eth0的虛擬ip

實戰(zhàn)二:

已知下面字符串是將RANDOM隨機數(shù)采用md5sum加密后任意取出的連續(xù)10位結(jié)果均抽,請破解這些字符串對應的md5sum前對的字符串的數(shù)字?
"4fe8bf20ed"

一其掂、預備知識
RANDOM的范圍是:0~32767
二油挥、思路:
1.)先將RANDOM隨機的所有可能寫成字典
2.)用腳本做密碼匹配

1)RANDOM字典的生成
#!/bin/bash
for n in {0..32767}
do
        echo "$(echo $n | md5sum) : $n" >> zhiwen.txt
done
echo "ok"
2)匹配密碼
#!/bin/bash

md5char="4fe8bf20ed" #要匹配的字符串

while read line #變量是line
do 
        if [ $(echo $line | grep $md5char | wc -l) -eq 1 ];then
                echo $line 
                break  #匹配到后就退出程序

        fi

done<zhiwen.txt #按行讀取字典
將上述代碼合并
#!/bin/bash

>zidian.txt #清空字典文件
for n in {0..32767}
do
        echo "$(echo $n |md5sum) : $n" >>zidian.txt  #此處不能是">"
done
echo "input ok"

md5char="4fe8bf20ed" #要破解密碼


while read line
do
        if [ $(echo $line | grep $md5char |wc -l ) -eq 1 ];then 
                echo $line
                break
        fi

done<zidian.txt

效果如圖:

[root@mycentos shell]# sh 7.sh 
1dcca23355272056f04fe8bf20edfce0 - : 5

二、數(shù)組

數(shù)組的操作

1.定義數(shù)組:
方式一:用小括號將變量值括起來賦值給數(shù)組變量,每個變量之間要用空格進行分格
[root@mycentos shell]# array=(1 2 3)
[root@mycentos shell]# echo ${array[*]}  #打印單個數(shù)組元素時用"${數(shù)組名[下標]}"深寥,當未指定數(shù)組下標時攘乒,數(shù)組的下標將從0開始。
1 2 3
方式二:用小括號將變量括起來惋鹅,同時1采用鍵值對的形式賦值
array=([1]=one [2]=two [3]=three)
小括號里對應的數(shù)字為數(shù)組下標则酝,等號后面的內(nèi)容為下標對應的數(shù)組變量的值。
[root@mycentos shell]# array=([1]=one [2]=twe [3]=three)
[root@mycentos shell]# echo ${array[1]}  
one
[root@mycentos shell]# echo ${array[2]}
twe
[root@mycentos shell]# echo ${array[3]}
three
[root@mycentos shell]# echo ${array[*]}
one twe three
此方式繁瑣闰集,不推薦

方法三:動態(tài)的定義數(shù)組變量沽讹,并使用命令的輸出結(jié)果作為數(shù)組內(nèi)容
array=($(命令))
或
array=(`命令`)

[root@mycentos Desktop]# touch array/{1..3}.txt
[root@mycentos Desktop]# ls -l array/
total 0
-rw-r--r--. 1 root root 0 Nov 15 14:44 1.txt
-rw-r--r--. 1 root root 0 Nov 15 14:44 2.txt
-rw-r--r--. 1 root root 0 Nov 15 14:44 3.txt
[root@mycentos Desktop]# array=($(ls array/))
[root@mycentos Desktop]# echo ${array[*]}
1.txt 2.txt 3.txt
------------------------------------------------------------------------------------------------
2.打印數(shù)組長度
echo {#數(shù)組名[*]}
數(shù)組是特殊的變量,變量子串的知識也試用武鲁。
------------------------------------------------------------------------------------------------
3.數(shù)組的賦值:
數(shù)組名[下標]=值
------------------------------------------------------------------------------------------------
4.數(shù)組的刪除:
由于數(shù)組本質(zhì)上是變量,則可通過unset 數(shù)組[下標]來清除相應的數(shù)組元素爽雄,如果不帶下標,則表示清除整個數(shù)組的所有數(shù)據(jù)沐鼠。
------------------------------------------------------------------------------------------------
5.數(shù)組內(nèi)容的截取和替換:
[root@mycentos ~]# array=(1 2 3 4 5)
[root@mycentos ~]# echo ${array[*]:1:3}   #從下標為1的元素開始截取3個數(shù)組元素
2 3 4
[root@mycentos ~]# array=({a..z})
[root@mycentos ~]# echo ${array[*]}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@mycentos ~]# echo ${array[*]:1:2}  #從下標為1的元素開始截取2個數(shù)組元素
b c 

[root@mycentos ~]# array=(1 2 3 4 5)
[root@mycentos ~]# echo ${array[*]/1/b}  #把數(shù)組的1替換成b,原來數(shù)組被修改和sed很像
b 2 3 4 5

替換方法:
${數(shù)組名[@或*]/查找字符/替換字符}挚瘟,該操作并不會改變原先數(shù)組的內(nèi)容。

例一:
使用循環(huán)批量輸出數(shù)組的元素

方式一:C語言型打印數(shù)組元素
#!/bin/bash
array=(1 2 3 4 5)
for ((i=0;i<${#array[*]};i++))
do
        echo ${array[i]}
done
方式二:
普通循環(huán)打印數(shù)組元素
#!/bin/bash
array=(1 2 3 4 5)
for n in ${array[*]} #<==${array[*]}表示輸出數(shù)組的所有元素饲梭,相當于列表數(shù)組元素
do
        echo $n
done
方式三:
#!/bin/bash
array=(1 2 3 4 5)
i=0
while ((i<${#array[*]}))
do
        echo ${array[i]}
        ((i++))
done

例二:通過豎向列舉法定義數(shù)組元素批量打印

#!/bin/bash
array=(
oldboy
oldgirl
xiaoming
xiaoqiang
)
for ((i=0;i<${#array[*]};i++))
do
        echo "this is num $i,then content is ${array[$i]}"
done
echo "array len:${#array[*]}"

結(jié)果如圖:

[root@mycentos arr]# sh 4.sh 
this is num 0,then content is oldboy
this is num 1,then content is oldgirl
this is num 2,then content is xiaoming
this is num 3,then content is xiaoqiang
array len:4

例三:
將命令結(jié)果作為數(shù)組元素定義并打印

#!/bin/bash
dir=($(ls ./*.txt))
for ((i=0;i<${#dir[*]};i++))
do
        echo "this is NO.$i,filename is ${dir[$i]}"

done

結(jié)果如圖:

[root@mycentos arr]# sh 5.sh 
this is NO.0,filename is ./1.txt
this is NO.1,filename is ./2.txt
this is NO.2,filename is ./3.txt
this is NO.3,filename is ./4.txt

關(guān)于數(shù)組的總結(jié):

1).定義:
靜態(tài)array=(1 2 3)
動態(tài)array=($(ls))
2).賦值:array[3]=4
3).打印:${array[*]}或${array[*]}
    數(shù)組長度:${#array[@]}或${#array[*]}
    單個元素:${array[i]}
4).循環(huán)打印
#!/bin/bash
arr=(
        10.0.0.11
        10.0.0.22
        10.0.0.33
)
#<==C語言循環(huán)打印
for ((i=0;i<${#arr[*]};i++))
do
        echo "${arr[i]}"

done
echo '-----------------------------------'
#<==普通循環(huán)打印
for n in ${arr[*]}
do
        echo "$n"
done

實戰(zhàn)三

利用for循環(huán)打印下面這句話不大于6的單詞
I am lodboy teacher welcome to oldboy training class

計算變量內(nèi)容長度方式:
[root@mycentos arr]# char=oldboy
[root@mycentos arr]# echo char | wc -L 6 [root@mycentos arr]# echo{char}
oldboy
[root@mycentos arr]# echo {#char} 6 [root@mycentos arr]# expr lengthchar
6
[root@mycentos arr]# expr char | awk '{print length(0)}'
6

方式一(數(shù)組實現(xiàn)):
#!/bin/bash
arr=(I am oldboy teacher welcome to oldboy training class)

for ((i=0;i<${#arr[*]};i++))
do
        #if [ $(expr length ${arr[i]}) -lt 6 ];then
        #       echo ${arr[i]}
        #fi

        if [ ${#arr[i]} -lt 6 ];then
                echo ${arr[i]}
        fi
done

方式二(列表實現(xiàn)):#!/bin/bash
for word in I am oldboy teacher welcome to oldboy training class
do
        if [ ${#word} -lt 6 ];then

                echo $word
        fi

done
方法三(awk循環(huán)):
[root@mycentos arr]# char="I am oldboy teacher welcome to oldboy training class"
[root@mycentos arr]# echo $char | awk '{for(i=1;i<=NF;i++) if(length($i)<6)print $i}' 
I
am
to
class

實戰(zhàn)四

檢測多個網(wǎng)站地址是否正常
要求:
1)使用shell數(shù)組的方法實現(xiàn)乘盖,檢測策略盡量使用模擬用戶訪問
2)每10秒進行一次全部檢測,無法訪問的輸出報警
3)待檢測的地址如下
http://www.baidu.com
http://www.sina.com
http://www.qq.com
http://www.1.com

思路:
一憔涉、網(wǎng)站放到數(shù)組中
二订框、編寫URL檢測腳本,傳入數(shù)組的元素监氢,即URL
三布蔗、組合實現(xiàn)整個案例,編寫main的主函數(shù)(即執(zhí)行函數(shù))浪腐,每隔10秒檢查一次

#!/bin/bash

. /etc/init.d/functions


check_count=0

urlArr=(
        http://www.linuxprobe.com
        http://www.sina.com
        http://www.a.co
        http://www.baidu.com
)

function wait(){  #定義倒計數(shù)3纵揍、2、1函數(shù)

        echo -n "3秒后议街,執(zhí)行檢查URL的操作"
        for ((i=0;i<3;i++))
        do
                echo -n '.';sleep 1
        done
        echo

}
function check_url(){

        wait  #執(zhí)行倒計時函數(shù)
        for ((i=0;i<$(echo ${#urlArr[*]});i++))
        do
                wget -o /dev/null -T 5  --tries=1 --spider  ${urlArr[i]} &>/dev/null

                if [ $? -eq 0 ];then
                        action "${urlArr[i]}" /bin/true
                else
                        action "${urlArr[i]}" /bin/false
                fi
        done
        ((chenk_count++)) #檢測次數(shù)
}
function main(){

        while true
        do
                check_url
                echo "-------check count:${check_count}-----"
                sleep 1
        done
}
main

效果如圖:


未標題-1.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末泽谨,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子特漩,更是在濱河造成了極大的恐慌吧雹,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件涂身,死亡現(xiàn)場離奇詭異雄卷,居然都是意外死亡,警方通過查閱死者的電腦和手機蛤售,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門丁鹉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來妒潭,“玉大人,你說我怎么就攤上這事揣钦■ㄔ郑” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵冯凹,是天一觀的道長谎亩。 經(jīng)常有香客問我,道長宇姚,這世上最難降的妖魔是什么匈庭? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮空凸,結(jié)果婚禮上嚎花,老公的妹妹穿的比我還像新娘。我一直安慰自己呀洲,他們只是感情好紊选,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著道逗,像睡著了一般兵罢。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上滓窍,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天卖词,我揣著相機與錄音,去河邊找鬼吏夯。 笑死此蜈,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的噪生。 我是一名探鬼主播裆赵,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼跺嗽!你這毒婦竟也來了战授?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤桨嫁,失蹤者是張志新(化名)和其女友劉穎植兰,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體璃吧,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡楣导,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了畜挨。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爷辙。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡彬坏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出膝晾,到底是詐尸還是另有隱情,我是刑警寧澤务冕,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布血当,位于F島的核電站,受9級特大地震影響禀忆,放射性物質(zhì)發(fā)生泄漏臊旭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一箩退、第九天 我趴在偏房一處隱蔽的房頂上張望离熏。 院中可真熱鬧,春花似錦戴涝、人聲如沸滋戳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽奸鸯。三九已至,卻和暖如春可帽,著一層夾襖步出監(jiān)牢的瞬間娄涩,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工映跟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蓄拣,地道東北人。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓努隙,卻偏偏與公主長得像球恤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子剃法,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容