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:

  1. #!/bin/bash
  2. #功能:单分支if结构整数比较,用-lt格式例子
  3. if[10-lt12]
  4. then
  5. echo"yes"
  6. fi
  7.  
  8. 执行结果:
  9. [root@XCNif]#shtest1.sh
  10. yes
  11. #提示:当比较条件为整数数字时


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

解答:

特别强调:read读入和命令行传参是两种输入内容方法

1)脚本传参的方式脚本例子

  1. #!/bin/bash
  2. if[$1-lt$2]:then
  3. echo"yes,$1lessthen$2"
  4. fi
  5.  
  6. 输入结果
  7. [root@XCNif]#shif2.sh12
  8. yes,1lessthen2

2)单分支if判断两整数大小三种情况的脚本例子(以read读入为例)

  1. #!/bin/bash
  2. read-p"plsinputtwonum:"ab
  3. if[$a-lt$b];then
  4. echo"yes,$alessthan$b"
  5. exit
  6. fi
  7. if[$a-eq$b];then
  8. echo"yes,$aeaual$b"
  9. exit
  10. fi
  11. if[$a-gt$b];then
  12. echo"yes,$agreaterthan$b"
  13. exit
  14. fi
  15.  
  16.  
  17. 见证奇迹的时刻:
  18. [root@localhostshell]#shif1.sh
  19. plsinputtwonum:12
  20. yes,1lessthan2


范例3:开发shell脚本实现如果/server/scipts下面存在if3.sh的内容输出到屏幕

注意:如果执行脚本后发现该if3.sh不存在,就自动创建这个if3.sh脚本

  1. #!/bin/bash
  2. path=/server/scripts
  3. file=if3.sh
  4. #no1
  5. if[!-d$path]
  6. then
  7. mkdir-p$path
  8. echo"$pathisnotexist,alreadycreatedit."
  9. fi
  10. #no2
  11. if[!-f$path/$file]
  12. then
  13. touch$path/$file
  14. echo"$fileisnotexist,alreadtcreatedit."
  15. exit
  16. fi
  17. #no3
  18. echo"ls-l$path/$file"
  19. ls-l$path/$file
  20. ~
  21. 执行输出
  22.  
  23. [root@localhost~]#shif.sh
  24. /server/scriptsisnotexist,alreadycreatedit.
  25. if3.shisnotexist,alreadtcreatedit.


范例4:开发脚本判断系统剩余内存大小,如果低于100M就邮件报警。

测试报警成功后加入系统定时任务每3分钟执行一次检查。


思路:

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

  1. [root@ailuoli~]#free-m|grepbuffers/|awk'{print$NF}'
  2. 1781

2.发邮件mail,mutt。sendmail服务器要开启

  1. [root@ailuoli~]#yuminstallsendmail
  2. [root@ailuoli~]#/etc/init.d/sendmailstart
  3. Startingsendmail:[OK]
  4. Startingsm-client:[OK]
  5.  
  6. [root@ailuoli~]#echo"xcn"|mail-s"title"995345781@qq.com

3.编写脚本

  1. #!/bin/bash
  2. userd_mem=`free-m|grepbuffers/|awk'{print$NF}'`
  3. if[$userd_mem-lt100]
  4. then
  5. echo"menmisnotenough,$userd_men."|mail-s"memwarning$(date+%F)"995345781@qq.com
  6. fi

wKiom1lQxDKzLGYzAABrA331L8U422.png-wh_50

三分钟监测一次:

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

猜你在找的Bash相关文章