1. 程式人生 > >第二十三章 SHELL指令碼-CENTOS7.5知識

第二十三章 SHELL指令碼-CENTOS7.5知識


shell指令碼(三)

. 使用if條件語句

clip_image002

案例:

#!/bin/bash

echo "===Check disk usage...==="

DISKU=df -h|awk '/vda1/{print $5}'|awk -F% '{print $1}'

if [ $DISKU -gt 10 ] ; then

echo "warning,Disk vda1 is over 90 usages....."

echo "warning,Disk vda1 is over 90 usages....."> /var/log/diskusage.log

else

echo "disk vda1 is normal.Good luck."

fi

1).根分割槽已用空間>80%則報警,否則不執行任何操作

#!/bin/bash

echo "===Check disk usage...==="

DISKU=df -h|awk '/vda1/{print $5}'|awk -F% '{print $1}'

if [ $DISKU -gt 10 ] ; then

echo "warning,Disk vda1 is over 90 usages....."

echo "warning,Disk vda1 is over 90 usages....."> /var/log/diskusage.log

else

echo "disk vda1 is normal.Good luck."

fi

2).判斷/tmp目錄下是否有win目錄,若不存在則建立目錄,存在不執行任何操作

#!/bin/bash

if [ ! -e /tmp/win ] ;then

echo "To create dir win"

mkdir /tmp/win

elif [ -f /tmp/win ] ;then

echo "To del win file"

rm -rf /tmp/win

echo "To create dir win"

mkdir /tmp/win

else

echo "此目錄win已經存在了。"

fi

3).判斷httpd是否已經啟動,若已啟動,則提示已執行,否則啟動httpd服務

Systemctl status httpd

If [ $? -eq 0 ]

Then

Echo “Service httpd is running.”

Else

Systemctl start httpd

Fi

4).執行指令碼時指定IP,結果為ping該主機,若通,則顯示up,否則顯示down

#!/bin/bash

ping -c2 172.18.199.10&>> /dev/null

if [ $? -eq 0 ]

then

echo "The IP $1 is up."

else

echo "The IP $1 is down."

fi

示例:

指令碼可互動輸入分數,並判斷分數在90-100之間,判斷為優秀,60-89之間為合格,59-40以下其他為不及格努力;39以下復讀,其它輸入為非法輸入。

#!/bin/bash

echo "=======Test========"

read -p "請輸入你的成績" Source

if [ $Source -gt 100 ] ; then

echo "輸入錯誤"

elif [ $Source -lt 0 ] ; then

echo "輸入錯誤"

elif [ $Source -ge 90 ] ; then

echo "優秀"

elif [ $Source -ge 60 ] ; then

echo "及格"

elif [ $Source -ge 40 ] ; then

echo "努力"

else

echo "復讀";

fi

二、迴圈語句:

clip_image004

clip_image006

1FOR迴圈寫法

for((i=1;i<=10;i++));

for i in `seq 10`

for i in {1..10}

#!/bin/bash

for i in {1..10}

do

echo “$i”

done

#!/bin/bash

for i in $*

Do

Echo “$i”

Done

for i in {30..39}

do

echo $i

done

vim num.txt

#!/bin/bash

for i in `cat num.txt`

Do

Echo “$i”

Done

#!/bin/bash

ipnet='172.18.11.'

for IPaddress in {1..254}

do

ping -c 1 $ipnet$IPaddress &> /dev/null

if [ $? -eq 0 ] ; then

echo "This host $ipnet$IPaddress is up."

echo "This host $ipnet$IPaddress is up." >> /tmp/ping-18net.log

else

echo "This host $ipnet$IPaddress is down."

fi

done

echo "Net18 ping ok."

#!/bin/bash

for (( i = 1; i <=9; i++ ))

do

for (( j=1; j <= i; j++ ))

do

let "chengji = i * j"

echo -n "$i*$j=$chengji "

done

echo ""

done

2while迴圈寫法

clip_image008

如:

i=1

while [ $i -lt 10 ]

do

echo $i

let i++

done

i++ 等同於 i=i+1

i+=1 等同於 i=i+1

i+=2 i=i+2

i-- i=i-1

i-=2 i=i-2

i*=2 i=i*2

迴圈結構中數值增量需要與let合作,如let i++

作業:用指令碼完成

1.公司要求新進一批實習生,要為他們建立使用者名稱shixi01 ---- shixi10,要求所有人的密碼初始都為great123。

2.用FOR迴圈寫九九乘法表。

3.用for及while結構分別完成掃描本網段址的指令碼