单分支结构
语法:
if [条件]
then
指令
fi
或
if [条件]:then
指令
fi
if单分支条件中文编程语法:
如果 [你有房]
那么
我就嫁给你
果如
提示:分号相当于命令换行,上面两种语法等用。
特殊写法:if [-f "$file1"];then echo 1;if 相当于:[if "$file1"]&& echo 1
if [ -f "$file1" ] :then
echo 1
fi
范例1:
范例2:使用read及脚本传参方式如果实现上述整数的比较?
解答:
1)脚本传参的方式脚本例子
- #!/bin/bash
- if[$1-lt$2]:then
- echo"yes,$1lessthen$2"
- fi
- 输入结果
- [root@XCNif]#shif2.sh12
- yes,1lessthen2
2)单分支if判断两整数大小三种情况的脚本例子(以read读入为例)
- #!/bin/bash
- read-p"plsinputtwonum:"ab
- if[$a-lt$b];then
- echo"yes,$alessthan$b"
- exit
- fi
- if[$a-eq$b];then
- echo"yes,$aeaual$b"
- exit
- fi
- if[$a-gt$b];then
- echo"yes,$agreaterthan$b"
- exit
- fi
- 见证奇迹的时刻:
- [root@localhostshell]#shif1.sh
- plsinputtwonum:12
- yes,1lessthan2
范例3:开发shell脚本实现如果/server/scipts下面存在if3.sh的内容就输出到屏幕
注意:如果执行脚本后发现该if3.sh不存在,就自动创建这个if3.sh脚本
- #!/bin/bash
- path=/server/scripts
- file=if3.sh
- #no1
- if[!-d$path]
- then
- mkdir-p$path
- echo"$pathisnotexist,alreadycreatedit."
- fi
- #no2
- if[!-f$path/$file]
- then
- touch$path/$file
- echo"$fileisnotexist,alreadtcreatedit."
- exit
- fi
- #no3
- echo"ls-l$path/$file"
- ls-l$path/$file
- ~
- 执行输出:
- [root@localhost~]#shif.sh
- /server/scriptsisnotexist,alreadycreatedit.
- if3.shisnotexist,alreadtcreatedit.
范例4:开发脚本判断系统剩余内存大小,如果低于100M就邮件报警。
测试报警成功后加入系统定时任务每3分钟执行一次检查。
思路:
如果去内容,去内存那个选项。
- [root@ailuoli~]#free-m|grepbuffers/|awk'{print$NF}'
- 1781
2.发邮件mail,mutt。sendmail服务器要开启
- [root@ailuoli~]#yuminstallsendmail
- [root@ailuoli~]#/etc/init.d/sendmailstart
- Startingsendmail:[OK]
- Startingsm-client:[OK]
- [root@ailuoli~]#echo"xcn"|mail-s"title"995345781@qq.com
3.编写脚本
- #!/bin/bash
- userd_mem=`free-m|grepbuffers/|awk'{print$NF}'`
- if[$userd_mem-lt100]
- then
- echo"menmisnotenough,$userd_men."|mail-s"memwarning$(date+%F)"995345781@qq.com
- fi
三分钟监测一次:
*/3 * * * * /bin/bash /mem.sh