七、if結構條件句知識與實踐
(一)if條件句單雙分支語法
1、單分支
if 條件
then
指令
fi
2、雙分支
if 條件
then
指令
else
指令集2
fi
(二)if條件句多分支陳述句
if 條件1
then
指令1
elif 條件2
then
指令2
elif 條件3
then
指令3
else
指令4
fi
實體:
如果不存在目錄/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 ]判斷引數是否為兩個,
列印一個安裝選單:
[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]#
八、函式知識與實踐
(一)shell函式語法
第一種語法 第二種語法 第三種語法
function 函式名(){ } function 函式名 {} 函式名() { }
實體
[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]#
九、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]#
十、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(運維人員)
常用命令:
- kill,killall,pkill :殺掉行程
- ps:查看行程,
- pstree:顯示行程狀態樹,
- top:顯示行程,
- renice:改變優先權,
- nohup:用戶退出系統之后繼續作業,
- pgrep:查找匹配條件的行程,
- strace:跟蹤一個行程的系統呼叫情況,
- ltrace:跟蹤行程呼叫庫函式的情況,
(三)范例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
十一、for回圈陳述句應用實踐
(一)、for回圈語法
1)普通語法
for 變數名 in 變數取值串列
do
指令,,,
done
2)c語言型for回圈語法
for(( exp1;exp2;exp3))
do
指令,,,
done
(一)范例1
用for回圈豎向列印1、2、3、4、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
十二、回圈控制及狀態回傳值應用實踐
本章將帶著大家學習以下幾個特殊的命令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值,
十三、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=(`命令`)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/43567.html
標籤:其他
上一篇:模塊一:shell 腳本基礎
下一篇:模塊三、企業實戰案例
