1.格式
if [ 条件判断式 ];then
条件成立时,执行的程序
else
条件不成立时,执行的语句
fi
2.练习3:判断输入的是否是一个目录
[root@catyuan ~]# vim if3.sh
#!/bin/bash
read -t 30 -p "Please input dir:" dir #使用read命令创建一个键盘录入,等待30s,变量为dir
if [ -d "$dir" ];then #判断输入的内容是否为目录
echo "it is dir" #是目录的话输出这句话
else
echo "it is not dir" #不是目录的话输出这句话
fi
[root@catyuan ~]# chmod 755 if3.sh
[root@catyuan ~]# ./if3.sh
Please input dir:/
it is dir
[root@catyuan ~]# ./if3.sh
Please input dir:d
it is not dir
3.练习4:判断Apache服务是否启动
思路:
[root@catyuan ~]# ps aux | grep httpd
root 12603 0.0 0.0 112660 968 pts/1 R+ 08:51 0:00 grep --color=auto httpd
[root@catyuan ~]# ps aux | grep httpd | grep -v grep
[root@catyuan ~]# systemctl start httpd
[root@catyuan ~]# ps aux | grep httpd | grep -v grep #取反,去掉有grep的那行
root 12622 0.4 0.2 226240 5116 ? Ss 08:52 0:00 /usr/sbin/httpd -DFOREGROUND
apache 12631 0.0 0.1 228324 3148 ? S 08:53 0:00 /usr/sbin/httpd -DFOREGROUND
apache 12632 0.0 0.1 228324 3148 ? S 08:53 0:00 /usr/sbin/httpd -DFOREGROUND
apache 12633 0.0 0.1 228324 3148 ? S 08:53 0:00 /usr/sbin/httpd -DFOREGROUND
apache 12634 0.0 0.1 228324 3148 ? S 08:53 0:00 /usr/sbin/httpd -DFOREGROUND
apache 12635 0.0 0.1 228324 3148 ? S 08:53 0:00 /usr/sbin/httpd -DFOREGROUND
编写脚本
[root@catyuan ~]# systemctl stop httpd
[root@catyuan ~]# vim if4.sh
#!/bin/bash
test=$(ps aux | grep httpd | grep -v grep) #截取httpd进程,并把结果赋予变量test
if [ -n "$test" ];then #如果test的值不为空,则执行then后的语句
echo "$(date) httpd is ok" >> /tmp/autostart-acc.log #将httpd is ok这句话及日期写入正确日志文件中
echo "apache is ok"
else
echo "apache is not ok"
systemctl start httpd &> /dev/null #Apache的标准启动命令,并且将这条命令的结果丢入黑洞文件/dev/null,不在屏幕显示
echo "$(date) restart httpd" >> /tmp/autostart-err.log #将重启httpd这句话及日期写入错误文件中
fi
[root@catyuan ~]# chmod 755 if4.sh
[root@catyuan ~]# ./if4.sh
apache is not ok
[root@catyuan ~]# vi /tmp/sutostart-err.log #之前关闭了Apache服务,所以写入错误日志文件并重启,此时的正确日志文件没有内容
Tue Jul 2 01:09:34 CST 2019 restart httpd
[root@catyuan ~]# ./if4.sh
apache is ok
[root@catyuan ~]# vim /tmp/autostart-acc.log
Tue Jul 2 01:12:55 CST 2019 httpd is ok #再次执行脚本,由于之前已经重启服务,所以写入正确日志文件
注意:这个脚本的文件名不能出现包含有httpd,否则会出错。无论Apache服务是否正常,都会显示apache is ok。也可以通过检测端口来判断Apache服务