- 单分支的if语句:
if 条件测试操作
then
命令序列
fi
例:判断挂载点目录是否存在,若不存在则新建此目录。
[[email protected] script]# cat chkmountdir.sh
#!/bin/bash
MOUNT_DIR="/media/cdrom"
if [ ! -d $MOUNT_DIR ]
then
mkdir -p $MOUNT_DIR
fi
[[email protected] script]# chmod +x chkmountdir.sh
[[email protected] script]# ./chkmountdir.sh
[[email protected] script]# ls /media/
cdrom RHEL_6.5 x86_64 Disc 1
例:若当前用户不是root,则提示报错:
[[email protected] script]# cat chkifroot.sh
#!/bin/bash
if [ "$USER" != "root" ];then
echo "错误:非root用户,权限不足!"
exit 1
fi
fdisk -l /dev/sda
[[email protected] script]# chmod +x chkifroot.sh
[[email protected] 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
[[email protected] script]# su - oracle
[[email protected] ~]$ source /script/chkifroot.sh
错误:非root用户,权限不足!
2.双分支的if语句:
if 条件测试操作
then
命令序列1
else
命令序列2
fi
例:编写一个连通性的测试脚本,通过位置参数$1提供目标主机地址。然后根据ping检测结果给出相应的提示。
[[email protected] 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
[[email protected] script]# chmod +x ping.sh
[[email protected] script]# ./ping.sh 192.168.1.11
Host 192.168.1.11 is up.
[[email protected] script]# ./ping.sh 192.168.1.12
Host 192.168.1.12 is down.
例:通过shell脚本检查httpd服务是否运行;
[[email protected] 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
[[email protected] script]# chmod +x chkhttpd.sh
[[email protected] script]# ./chkhttpd.sh
警告:httpd服务不可用
[[email protected] script]# service httpd start
[[email protected] script]# ./chkhttpd.sh
监听地址::::80
进程PID号:2398
3.多分支if语句
if 条件测试操作1
then
命令序列1
elif 条件测试操作2
then
命令序列2
else
命令序列3
fi
例:编写一个成绩分档脚本;
[[email protected] 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
[[email protected] script]# chmod +x gradediv.sh
[[email protected] script]# ./gradediv.sh
请输入你的成绩[0-100]:100
100 分!你分数很牛逼
[[email protected] script]# ./gradediv.sh
请输入你的成绩[0-100]:78
78 分!还行吧小伙子
[[email protected] script]# ./gradediv.sh
请输入你的成绩[0-100]:50
50 分!你是个垃圾
就到这吧,慢慢积累