

then后面跟符合条件之后执行的程序,可以放在[]之后,用;分隔。也可以换行写入,就不需要“;”了。
比如:
if [ 条件判断式 ] then 程序 fi
#!/bin/bash#date:2022-4-13#描述:if单分支语句示例,判断目录是否存在read -p "请输入需要判断的目录:" nameif [ ! -d $name ] then echo "$name目录不存在,正在创建..." mkdir -p $name echo "$name目录创建完成."fi echo "$name目录已存在,正在退出..."
if [ 条件判断式 ] then 条件成立时,执行的程序。 else 条件不成立时,执行的另一个程序。 fi
在日常工作中,服务器上的服务经常会宕机。如果我们对服务器监控不好,就会造成服务器中服务宕机了,而管理员却不知道的情况。这是我们可以写一个脚本来监听本机的服务。如果服务停止或宕机了,可以自动重启这些服务。用apache举例:
首先介绍端口扫描命令:nmap端口扫描命令,格式:nmap -sT 域名或IP。
子选项:
-s 扫描 -T 扫描所有开启的TCP端口
nmap扫描后显示的端口一定是存活的。
脚本要使用nmap命令,首先用yum -y install nmap安装。
apache服务也是yum安装。
[root@xiaopeng ~]# cat autostart.sh #!/bin/bash port=$(nmap -sT 192.168.22.222 | grep tcp | grep http | awk '{print $2}') if [ "$port" == "open" ] then echo "$(date) httpd is ok!" >> /tmp/autostart-acc.log else /etc/rc.d/init.d/httpd start &> /dev/nullecho "$(date) restart httpd!!" >> /tmp/autostart-err.log fi
首先用nmap命令查看是否开启apache并赋值给port。
然后进行条件判断。如果服务开启,输出当前时间+httpd is ok 到/tmp/autostart-
acc.log。
如果变量port的值不是open,那么执行else下操作。首先启动apache服务,将启动后 信息输出至位桶,然后在/tmp/autostart-err.log中记录。在本次脚本中nmap命令使用的是。
IP查找端口,但并未指DNS,所以会报DNS不存在的错,但不影响结果。
if [ 条件判断式1 ] then 当条件判断式1成立时,执行程序1。 elif [ 条件判断式2 ] then 当条件判断式2成立时,执行程序2。 ......(可加入更多条件) else 当所有条件不成立时,最后执行此程序。 fi
#!/bin/bash #date:2022-4-13 #描述:判断文件类型 read -p "请输入一个文件:" file if [ -z $file ] then echo "错误!输入的文件为空." elif [ ! -e $file ] then echo "错误!输入的文件不存在." elif [ -f $file ] then echo "$file是一个普通文件" elif [ -d $file ] then echo "$file是一个目录" else echo "$file是其他类型文件" fi
多分支case条件语句:
case $变量名 in “值1”) 如果$变量等于值1,则执行程序1 ;; “值2”) 如果$变量等于值2,则执行程序2 ;; ....省略... *) 如果$变量的值不是以上值,则执行此程序 ;; esac
[root@xiaopeng htdocs]# vim /etc/init.d/apached #!/bin/bash # chkconfig: 2345 64 36 # description: A very fast and reliable SQL database engine httpd=/usr/local/apache2/bin/apachectl case $1 in start) $httpd start ;; stop) $httpd stop ;; restart) $0 stop sleep 0.05 $0 start ;; configtest) $httpd -t ;; *) echo "usage:$0 start|stop|restart|configtest." ;; esac
[root@xiaopeng conf]# vim /etc/init.d/nginx #!/bin/bash #Author:liu #chkconfig: 2345 99 33 #description: nginx server control tools ngxc="/usr/local/nginx/sbin/nginx" ngxc_fpm="/usr/local/php/sbin/php-fpm" case "$1" in start) $ngxc -t &> /dev/null if [ $? -eq 0 ];then $ngxc $ngxc_fpm echo "nginx service start success!" else $ngxc -t fi ;; stop) $ngxc -s stop killall php-fpm echo "nginx service stop success!" ;; restart) $0 stop $0 start ;; reload) $ngxc -t &> /dev/null if [ $? -eq 0 ];then $ngxc -s reload pkill -HUP php-fpm echo "reload nginx config success!" else $ngxc -t fi ;; *) echo "please input stop|start|restart|reload." exit 1 esac
推荐阅读
>>>新手必备-Linux系统安装配置+Xshell远程连接
运维界升职加薪必备的云计算技术,你学了吗?
学完高级运维云计算课程之后,你可以:
跨越90%企业的招聘硬门槛
增加70%就业机会
拿下BAT全国TOP100大厂敲门砖
体系化得到运维技术硬实力
技术大佬年薪可达30w+