7、if結構條件句知識與實踐web
(一)if條件句單雙分支語法shell
一、單分支 if 條件 then 指令 fi 二、雙分支 if 條件 then 指令 else 指令集2 fi
(二)if條件句多分支語句編程
if 條件1 then 指令1 elif 條件2 then 指令2 elif 條件3 then 指令3 else 指令4 fi
實例:centos
若是不存在目錄/backup,則建立。 [root@centos6-kvm3 scripts]# cat 07-01.sh #!/bin/bash path="/backup" [ -d $path ] || mkdir $path -p if [ -d $path ] then : else mkdir $path -p fi if [ !-d $path] then mkdir $path -p fi [root@centos6-kvm3 scripts]# 開發shell腳本判斷內存是否充足,若是小於100,提示不足,若是大於100提示充足。 [root@centos6-kvm3 scripts]# cat 07-02.sh #!/bin/bash mem=`free -m | awk 'NR==3{print $NF}'` if [ $mem -lt 100 ] then echo "內存不充足!" else echo "內存充足!" fi [root@centos6-kvm3 scripts]#
判斷兩個整數大小:數組
[root@centos6-kvm3 scripts]# cat 07-03.sh #!/bin/bash read -p "請輸入兩個整數:" a b expr $a + $b + 1 &>/dev/null if [ $? -ne 0 ] then echo "請輸入兩個整數。" exit 0 fi if [ -z "$b" ] then echo "請輸入兩個整數。" exit 1 fi if [ $a -lt $b ] then echo "$a小於$b" elif [ $a -gt $b ] then echo "$a大於$b" else echo "$a等於$b" fi [root@centos6-kvm3 scripts]# 若是使用傳參方式: [$# -ne 2 ]判斷參數是否爲兩個。
打印一個安裝菜單:bash
[root@centos6-kvm3 scripts]# cat 07-04.sh #!/bin/bash cat <<EOF 1.install lamp 2.install lnmp 3.exit EOF read -p "請輸入一個數字{1|2|3}:" n expr $n + 2 &>/dev/null if [ $? -ne 0 ] then echo "usage:$0{1|2|3}" exit 0 fi if [ $n -eq 1 ] then echo "install lamp" elif [ $n -eq 2 ] then echo "install lnmp" elif [ $n -eq 3 ] then echo "exit" else echo "usage:$0{1|2|3}" fi [root@centos6-kvm3 scripts]#
8、函數知識與實踐app
(一)shell函數語法運維
第一種語法 第二種語法 第三種語法
function 函數名(){ } function 函數名 {} 函數名() { }dom
實例ssh
[root@centos6-kvm3 scripts]# cat 08-01.sh #!/bin/bash function oldboy(){ echo "i am $1 teacher" } function oldgirl { echo "i am $1 teacher" } test() { echo "this is $1" } oldboy $1 oldgirl $2 test $3 [root@centos6-kvm3 scripts]# bash 08-01.sh oldboy oldgirl test i am oldboy teacher i am oldgirl teacher this is test [root@centos6-kvm3 scripts]#
實例:檢測web網站是否正常
wget 命令:
--spider 模擬爬蟲
-q 安靜訪問
-o /dev/null 不輸出
-T --timeout 超時時間
-t --tries 重試次數
wget --spider -T 5 -q -o /dev/null -t 2 www.baidu.com echo $?
curl命令:
-I 查看響應頭
-s 安靜的
-o /dev/null 不輸出
-w%{http_code} 返回狀態碼
[root@centos6-kvm3 scripts]# curl -I -s -o /dev/null -w "%{http_code}\n" www.baidu.com 200 [root@centos6-kvm3 scripts]#
案例:
[root@centos6-kvm3 scripts]# cat 08-02.sh #!/bin/bash function usage(){ echo "usage:$0 url" exit 1 } function url_check { wget -q -o /dev/null -T 5 -t 3 $1 if [ $? -eq 0 ] then echo "$1 is ok!" else echo "$1 is fail!" fi } main(){ if [ $# -ne 1 ] then usage else url_check $1 fi } main $* [root@centos6-kvm3 scripts]#
9、case結構條件句應用時間
(一)case語法結構
case結構條件句至關於多分支if條件語句,可是它比這些條件句看起來更規範工整,常被用於實現系統服務腳本等應用場景中。
case語句的語法結構:
case "變量" in 值1) 指令1 ;; 值2) 指令2 ;; 值3) 指令3 ;; *) 指令4 esac
(二)實例1:
[root@centos6-kvm3 scripts]# cat 09-03.sh #!/bin/bash cat <<EOF 1.install lnmp 2.install lamp 3.exit EOF read -p "請輸入一個數字{1|2|3}:" num expr $num + 2 &>/dev/null if [ $? -ne 0 ] then echo "usage:$0{1|2|3}" exit 1 fi case $num in 1) echo "install lnmp" ;; 2) echo "install lamp" ;; 3) echo "exit" exit ;; *) echo "usage:$0{1|2|3}" exit 1 esac [root@centos6-kvm3 scripts]#
(三)實例2:
當用戶輸入對應的數字選擇水果的時候,告訴他選擇的水果是什麼,並給水果單詞加上一種顏色(隨意),要求用case語句實現。
內容的顏色用數字表示,範圍爲30-37,每一個數字表明一種顏色。 echo -e "\033[30m 黑色字oldboy trainning \033[0m" #<==30m表示黑色字。 echo -e "\033[31m 紅色字oldboy trainning \033[0m" #<==31m表示紅色字。 echo -e "\033[32m 綠色字oldboy trainning \033[0m" #<==32m表示綠色字。 echo -e "\033[33m 棕色字oldboy trainning \033[0m" #<==33m表示棕色字(brown),和黃色字相近。 echo -e "\033[34m 藍色字oldboy trainning \033[0m" #<==34m表示藍色字。 echo -e "\033[35m 洋紅字oldboy trainning \033[0m" #<==35m表示洋紅色字(magenta),和紫色字相近。 echo -e "\033[36m 藍綠色oldboy trainning \033[0m" #<==36m表示藍綠色字(cyan),和淺藍色字相近。 echo -e "\033[37m 白色字oldboy trainning \033[0m" #<==37m表示白色字。
基礎腳本1:
[root@centos6-kvm3 scripts]# cat 09-04.sh #!/bin/bash cat <<EOF 1.apple 2.pear 3.banana 4.cherry EOF read -p "請輸入一個數字{1|2|3|4}:" num expr $num + 2 &>/dev/null if [ $? -ne 0 ] then echo "usage:$0 {1|2|3|4}" exit 1 fi case $num in 1) echo -e "\033[31m apple \033[0m" ;; 2) echo -e "\033[32m pear \033[0m" ;; 3) echo -e "\033[33m banana \033[0m" ;; 4) echo -e "\033[34m cherry \033[0m" ;; *) echo "usage:$0 {1|2|3|4}" exit esac [root@centos6-kvm3 scripts]#
高級腳本2:
顏色函數: [root@centos6-kvm3 scripts]# cat color.sh #!/bin/bash red="\033[31m" green="\033[32m" yellow="\033[33m" blue="\033[34m" tail="\033[0m" color(){ case $1 in red) echo -e "${red}$2${tail}" ;; green) echo -e "${green}$2${tail}" ;; yellow) echo -e "${yellow}$2${tail}" ;; blue) echo -e "${blue}$2${tail}" ;; *) echo "usage:$0 please input right content" esac } color $* [root@centos6-kvm3 scripts]# 功能調用顏色函數: [root@centos6-kvm3 scripts]# cat 09-04.sh #!/bin/bash . ./color.sh cat <<EOF 1.apple 2.pear 3.banana 4.cherry EOF read -p "請輸入一個數字{1|2|3|4}:" num expr $num + 2 &>/dev/null if [ $? -ne 0 ] then echo "usage:$0 {1|2|3|4}" exit 1 fi case $num in 1) color red apple ;; 2) color green pear ;; 3) color yellow banana ;; 4) color blue cheryy ;; *) echo "usage:$0 {1|2|3|4}" exit esac [root@centos6-kvm3 scripts]# 字的背景顏色對應的數字範圍爲40-47,代碼以下。 echo -e "\033[40;37m 黑底白字oldboy\033[0m" #<==40m表示黑色背景。 echo -e "\033[41;37m 紅底白字oldboy\033[0m" #<==41m表示紅色背景。 echo -e "\033[42;37m 綠底白字oldboy\033[0m" #<==42m表示綠色背景。 echo -e "\033[43;37m 棕底白字oldboy\033[0m" #<==43m表示棕色背景(brown),和黃色背景相近。 echo -e "\033[44;37m 藍底白字oldboy\033[0m" #<==44m表示藍色背景。 echo -e "\033[45;37m 洋紅底白字oldboy\033[0m" #<==45m表示洋紅色背景(magenta),和紫色背景相近。 echo -e "\033[46;37m藍綠底白字oldboy\033[0m" #<==46m表示藍綠色背景(cyan),和淺藍色背景相近。 echo -e "\033[47;30m 白底黑字oldboy\033[0m" #<==47m表示白色背景。
rsync啓動基本腳本:
[root@centos6-kvm3 scripts]# cat rsync.sh #!/bin/bash case $1 in start) rsync --daemon if [ $? -eq 0 ] then echo "rsync $1 ok" else echo "rsync $1 fail" fi ;; stop) killall rsync if [ $? -eq 0 ] then echo "rsync $1 ok" else echo "rsync $1 fail" fi ;; restart) killall rsync && sleep 1 && rsync --daemon if [ $? -eq 0 ] then echo "rsync $1 ok" else echo "rsync $1 fail" fi ;; *) echo "usage:$0 {start|stop|restart}" esac [root@centos6-kvm3 scripts]#
查看進程:lsof -i:873
rsync啓動高級腳本:
cp rsyncd.sh /etc/init.d/rsyncd
chkconfig --list rsyncd
chkconfig --add rsyncd
chmod +x /etc/init.d/rsyncd
[root@centos6-kvm3 scripts]# cat rsyncd.sh # chkconfig: 2345 20 80 # description: rsync start stop #!/bin/bash . /etc/init.d/functions start(){ rsync --daemon retval=$? if [ $retval -eq 0 ] then action "rsync start ok" /bin/true return $retval else action "rsync start fail" /bin/false return $retval fi } stop(){ killall rsync &>/dev/null retval=$? if [ $retval -eq 0 ] then action "rsync stop ok" /bin/true return $retval else action "rsync stop fail" /bin/false return $retval fi } case $1 in start) start retval=$? ;; stop) stop retval=$? ;; restart) stop sleep 2 start retval=$? ;; *) echo "usage:$0 {start|stop|restart}" esac exit $retval [root@centos6-kvm3 scripts]#
10、while循環
(一)while循環語法
while 循環語法 while <條件表達式> do 指令 done
(二)範例1:
每隔2s輸出系統負載狀況。
[root@centos6-kvm3 scripts]# cat 10-01.sh #!/bin/bash while true do uptime >>/tmp/oldboy.log sleep 2 done [root@centos6-kvm3 scripts]#
用法 說明
sh while1.sh & 把腳本while1.sh放到後臺執行(後臺運行腳本時經常使用)*
nohup while1.sh & 使用nohup 把腳本while.sh放到後臺執行。
ctl+c 中止執行當前腳本或者任務
ctl+z 暫停執行當前腳本或者任務
bg 把當前腳本或者任務放到後臺執行,bg能夠理解爲backround
fg 把當前腳本或者任務拿到前臺執行,若是有多個任務,可使用fg加任務編號調出對應腳本任務,如fg 2,調出第二個腳本任務,fg能夠理解爲frontground
jobs 查看當前執行的腳本或者任務
kill 關閉執行的腳本任務,即以「kill %任務編號」的形式關閉腳本,這個任務標號,能夠經過jobs得到。
後臺運行 & ,nohup,screen(運維人員)
經常使用命令:
(三)範例2:
請使用while循環對下面的腳本進行修改,使得當執行腳本時,每次執行完腳本之後不退出腳本了,而是繼續提示用戶輸入。
[root@centos6-kvm3 scripts]# cat 10-02.sh #!/bin/bash while true do read -t 15 -p "please input two number:" a b expr $a + $b + 2 &>/dev/null if [ $? -ne 0 ] then echo "usage:$0 please input two number." continue fi if [ -z "$b" ] then echo "usage:$0 please input two number." continue fi echo "a-b=$(($a-$b))" echo "a+b=$(($a+$b))" echo "a*b=$(($a*$b))" echo "a/b=$(($a/$b))" echo "a**b=$(($a**$b))" echo "a%b=$(($a%$b))" done [root@centos6-kvm3 scripts]#
(四)範例3:
猜數字遊戲。首先讓系統隨機生成一個數字,給這個數字定一個範圍(1-60),讓用戶輸入猜的數字,對輸入進行判斷,若是不符合要求,就給予高或低的提示,猜對後則給出猜對用的次數,請用while語句實現。
[root@centos6-kvm3 scripts]# cat 10-04.sh #!/bin/bash random=$((RANDOM%60)) count=0 while true do read -p "please input a num:" num ((count+=1)) if [ $random -lt $num ] then echo "你猜大了" elif [ $random -gt $num ] then echo "你猜小了" else echo "你猜對了,NB!共計猜了${count}次!" exit 1 fi done [root@centos6-kvm3 scripts]#
(五)範例4:
分析Apache訪問日誌(access_2010-12-8.log),把日誌中每行的訪問字節數對應字段數字相加,計算出總的訪問量。
[root@centos6-kvm3 scripts]# cat 10-05.sh #!/bin/bash sum=0 awk '{print $10}' access_2010-12-8.log | grep -v - >./oldboy.log while read line do ((sum=sum+line)) done <./oldboy.log echo $sum [root@centos6-kvm3 scripts]# sh 10-05.sh 1380681
11、for循環語句應用實踐
(一)、for循環語法
1)普通語法 for 變量名 in 變量取值列表 do 指令。。。 done 2)c語言型for循環語法 for(( exp1;exp2;exp3)) do 指令。。。 done
(一)範例1
用for循環豎向打印一、二、三、四、5共5個數字。
[root@centos6-kvm3 scripts]# cat 11-01.sh #!/bin/bash for n in {1..5} do echo $n done [root@centos6-kvm3 scripts]# sh 11-01.sh 1 2 3 4 5 [root@centos6-kvm3 scripts]#
(二)範例2:
經過開發腳本實現僅設置sshd rsyslog crond network sysstat服務開機自啓動。
[root@centos6-kvm3 scripts]# cat 11-02.sh #!/bin/bash for name in sshd rsyslog crond network sysstat do chkconfig $name on done [root@centos6-kvm3 scripts]# chkconfig --list | grep 3:on crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off network 0:off 1:off 2:on 3:on 4:on 5:on 6:off rsyslog 0:off 1:off 2:on 3:on 4:on 5:on 6:off sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off sysstat 0:off 1:on 2:on 3:on 4:on 5:on 6:off 擴展: [root@centos6-kvm3 scripts]# chkconfig --list | grep 3:on |awk '{print "chkconfig", $1, "off"}' | bash
(三)範例3:
計算從1加到100之和。
[root@centos6-kvm3 scripts]# cat 11-03.sh #!/bin/bash for n in {1..100} do ((sum=sum+$n)) done echo $sum [root@centos6-kvm3 scripts]# sh 11-03.sh 5050 [root@centos6-kvm3 scripts]# 方法2: for ((i=1;i<=100;i++)) do ((sum=sum+$i)) done echo $sum
(四)案例4:
在Linux下批量修改文件名,將文件名中的「_finished」去掉。
準備測試數據,以下。
方法1: ls *.jpg | awk -F "_finished" '{print "mv",$0, $1$2}'|bash 方法2: [root@centos6-kvm3 scripts]# cat 11-04.sh #!/bin/bash for file in `ls 11/*.jpg` do mv $file `echo ${file/_finished/}` done [root@centos6-kvm3 scripts]# 方法3: rename "_finished" "" *.jpg
12、循環控制及狀態返回值應用實踐
本章將帶着你們學習如下幾個特殊的命令break(循環控制)、continue(循環控制)、exit(退出腳本)、return(退出函數)。
(一)、break、continue、exit、return的區別和對比
在上述命令中,break、continue在條件語句及循環語句(for、while、if等)中用於控制程序的走向,而exit則用於終止全部語句並退出當前腳本,除此以外,exit還能夠返回上一次程序或命令的執行狀態值給當前Shell;return相似exit,只不過return僅用於在函數內部返回函數執行的狀態值。
命令 說明
break n 若是省略n表示跳出整個循環,n表示跳出循環的層數。
continue n 若是省略n表示跳過本次循環,忽略本次循環的剩餘代碼,進入循環的下一次循環。n表示退到第n層繼續循環。
exit n 退出當前shell程序,n爲上一次程序執行的狀態返回值。n也能夠省略,再下一個shell裏可經過$?接收exit n的n值。
return n 用於在函數裏,做爲函數的返回值,用於判斷函數執行是否正確。再下一個shell裏可經過$?接收exit n的n值。
十3、Shell數組應用實踐
(一)數組介紹
爲何會產生數組
一般在開發Shell腳本時,咱們定義變量採用的形式爲a=1;b=2;c=3,可若是有多個變量呢?這時再一個一個定義很費勁,而且要是有多個不肯定的變量內容,也難以進行變量定義,此外,快速讀取不一樣變量的值也是一件很痛苦的事情,因而數組就誕生了,它就是爲了解決上述問題而來的。
什麼是Shell數組
若是讀者有過其餘語言的編程經歷,那麼想必會熟悉數組的概念。簡單地說,Shell的數組就是把有限個元素(變量或字符內容)用一個名字命名,而後用編號對它們進行區分的元素集合。這個名字就稱爲數組名,用於區分不一樣內容的編號就稱爲數組下標。組成數組的各個元素(變量)稱爲數組的元素,有時也稱爲下標變量。
有了Shell數組後,就能夠用相同名字引用一系列變量及變量值,並經過數字(索引)來識別使用它們。在許多場合,使用數組能夠縮短和簡化程序開發。
(二)數組的定義
方法1:推薦 array=(one two three four) 方法2: array=([0]=one [1]=two [2]=three [3]=four) 方法3: [root@web01 ~]# array[0]=one [root@web01 ~]# array[1]=two [root@web01 ~]# array[2]=three [root@web01 ~]# array[3]=four [root@web01 ~]# echo ${array[@]} one two three four 方法4:命令的結果放到數組裏,推薦。 array=(`ls /server/scripts`)
(三)、操做數組元素
讀取數組內容:***** [root@web01 ~]# array=( 1 2 3 4 5) [root@web01 ~]# echo ${array[0]} 1 [root@web01 ~]# echo ${array[1]} 2 [root@web01 ~]# echo ${array[2]} 3 [root@web01 ~]# echo ${array[3]} 4 [root@web01 ~]# echo ${array[4]} 5 [root@web01 ~]# echo ${array[5]} [root@web01 ~]# echo ${array[*]} 1 2 3 4 5 [root@web01 ~]# echo ${array[@]} 1 2 3 4 5 [root@web01 ~]# echo ${#array[@]} 5 [root@web01 ~]# echo ${#array[*]} 5 給數組增長內容: [root@web01 ~]# array[5]=oldboy [root@web01 ~]# echo ${#array[*]} 6 [root@web01 ~]# echo ${array[*]} 1 2 3 4 5 oldboy 刪除數組元素: [root@web01 ~]# unset array[1] [root@web01 ~]# echo ${array[*]} 1 3 4 oldboy [root@web01 ~]# unset array[0] [root@web01 ~]# echo ${array[*]} 3 4 oldboy 數組能不能替換: 使用for循環打印數組元素 array=(1 2 3 4 5) for n in ${array[*]} do echo $n done echo ===================== #i爲數組下標 for ((i=0;i<${#array[*]};i++)) do echo ${array[i]} done array=([1]=one [2]=two [3]=three) array[0]=a;array[1]=b;array[2]=c array=($(命令)) 或 array=(`命令`)