if条件语句实战单分支结构

前端之家收集整理的这篇文章主要介绍了if条件语句实战单分支结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

单分支结构

语法:

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:

#!/bin/bash
#功能:单分支if结构整数比较,用-lt格式例子
if[10-lt12]
then
echo"yes"
fi

执行结果:
[root@XCNif]#shtest1.sh
yes
#提示:当比较条件为整数数字时


范例2:使用read及脚本传参方式如果实现上述整数的比较?

解答:

特别强调: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分钟执行一次检查。


思路:

  1. 如果去内容,去内存那个选项。

[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

wKiom1lQxDKzLGYzAABrA331L8U422.png-wh_50

三分钟监测一次:

*/3 * * * * /bin/bash /mem.sh

原文链接:https://www.f2er.com/bash/392520.html

猜你在找的Bash相关文章