單分支的if語句:
shell
if 條件測試操做
bash
thenoracle
命令序列ide
fi測試
例:判斷掛載點目錄是否存在,若不存在則新建此目錄。spa
[root@dbserver script]# cat chkmountdir.sh server
#!/bin/bash進程
MOUNT_DIR="/media/cdrom"ip
if [ ! -d $MOUNT_DIR ]ci
then
mkdir -p $MOUNT_DIR
fi
[root@dbserver script]# chmod +x chkmountdir.sh
[root@dbserver script]# ./chkmountdir.sh
[root@dbserver script]# ls /media/
cdrom RHEL_6.5 x86_64 Disc 1
例:若當前用戶不是root,則提示報錯:
[root@dbserver script]# cat chkifroot.sh
#!/bin/bash
if [ "$USER" != "root" ];then
echo "錯誤:非root用戶,權限不足!"
exit 1
fi
fdisk -l /dev/sda
[root@dbserver script]# chmod +x chkifroot.sh
[root@dbserver script]# ./chkifroot.sh
Disk /dev/sda: 53.7 GB, 53687091200 bytes
255 heads, 63 sectors/track, 6527 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000e59bd
Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 6528 51915776 8e Linux LVM
[root@dbserver script]# su - oracle
[oracle@dbserver ~]$ source /script/chkifroot.sh
錯誤:非root用戶,權限不足!
2.雙分支的if語句:
if 條件測試操做
then
命令序列1
else
命令序列2
fi
例:編寫一個連通性的測試腳本,經過位置參數$1提供目標主機地址。而後根據ping檢測結果給出相應的提示。
[root@dbserver script]# cat ping.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is up."
else
echo "Host $1 is down."
fi
[root@dbserver script]# chmod +x ping.sh
[root@dbserver script]# ./ping.sh 192.168.1.11
Host 192.168.1.11 is up.
[root@dbserver script]# ./ping.sh 192.168.1.12
Host 192.168.1.12 is down.
例:經過shell腳本檢查httpd服務是否運行;
[root@dbserver script]# cat chkhttpd.sh
#!/bin/bash
/etc/init.d/httpd status &>/dev/null
if [ $? -eq 0 ];then
echo "監聽地址:$(netstat -anpt |grep httpd | awk '{print $4}')"
echo "進程PID號:$(pgrep -x httpd)"
else
echo "警告:httpd服務不可用"
fi
[root@dbserver script]# chmod +x chkhttpd.sh
[root@dbserver script]# ./chkhttpd.sh
警告:httpd服務不可用
[root@dbserver script]# service httpd start
[root@dbserver script]# ./chkhttpd.sh
監聽地址::::80
進程PID號:2398
3.多分支if語句
if 條件測試操做1
then
命令序列1
elif 條件測試操做2
then
命令序列2
else
命令序列3
fi
例:編寫一個成績分檔腳本;
[root@dbserver script]# cat gradediv.sh
#!/bin/bash
read -p "請輸入你的成績[0-100]:" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ];then
echo "$GRADE 分!你分數很牛逼"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ];then
echo "$GRADE 分!還行吧小夥子"
else
echo "$GRADE 分!你是個垃圾"
fi
[root@dbserver script]# chmod +x gradediv.sh
[root@dbserver script]# ./gradediv.sh
請輸入你的成績[0-100]:100
100 分!你分數很牛逼
[root@dbserver script]# ./gradediv.sh
請輸入你的成績[0-100]:78
78 分!還行吧小夥子
[root@dbserver script]# ./gradediv.sh
請輸入你的成績[0-100]:50
50 分!你是個垃圾
就到這吧,慢慢積累