您的位置:首页 > 运维架构 > Shell

Shell脚本应用(五)if语句

2016-06-26 16:38 537 查看
单分支的if语句:

if 条件测试操作

then
命令序列
fi
例:判断挂载点目录是否存在,若不存在则新建此目录。
[root@dbserver script]# cat chkmountdir.sh
#!/bin/bash
MOUNT_DIR="/media/cdrom"
if [ ! -d $MOUNT_DIR ]
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 分!你是个垃圾
就到这吧,慢慢积累
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  语句 if