一、if条件语句

  1、语法

    1)单分支结构

第一种
if <条件表达式>
then
指令
fi 第二种
if <条件表达式>;then
指令
fi 上文的"<条件表达式>"部分可以时test、[]、[[]]、(())等条件表达式,甚至可以直接使用命令作为条件表达式。每个if语句都以if开头,并带有then,最后以fi结束
第二种语法中分号相当于命令换行,含义医院 当if后面的<条件表达式>成真时,就会执行then后面的指令或语句;否则,就会忽略then后面的指令或语句,转而执行fi下面的程序
条件语句还可以嵌套(就是if语句里面还有if条件语句)如下面语法示例:
if <条件表达式>
  then
    if <条件表达式>
      then
        指令
    fi
fi

    2)双分支结构

      复习一下单分支

        如果...,那么...

      双分支

        如果...,那么...,否则...

      结构如下:

if <条件表达式>
then
指令集1
else
指令集2
fi 测试条件表达式[ -f "$file1" ]&&echo || echo 0相当于下面:
if [ -f "$file1" ]
then
echo
else
echo
fi

    3)多分支结构

      结构主体

        如果...,那么...,否则如果...,那么...,否则如果...,那么...,否则...

      结构如下:

if <条件表达式1>
then
指令1
elif <条件表达式2>
then
指令2
else
指令3
fi
注意:每个elif都必须带then,else没有then

    4)条件表达式 test、[]、[[]]、(())等条件表达式语法

      1.4.1、test条件表达式

if test
then
指令
fi

      1.4.2、[]条件表达式

if [ 字符串或算术表达式 ]
then
指令
fi

      1.4.3、[[]]条件表达式

if [[ 字符串表达式 ]]
then
指令
fi

      1.4.4、(())条件表达式

if (( 算术表达式 ))
then
指令
fi

      1.4.5、命令表达式

if  命令
then
指令
fi

      

二、if条件语句示例

  1、单分支示例

    1)把下面测试文件中表达式的语句改成if条件语句

[root@web1 scripts]# [ -f /etc/hosts ]&& echo 1
1

[root@web1 scripts]# [[ -f /etc/hosts ]]&& echo 1
 1
 [root@web1 scripts]# test -f /etc/hosts && echo 1
 1

[root@web1 scripts]# chmod +x test15
chmod: cannot access ‘test15’: No such file or directory
[root@web1 scripts]# chmod +x test15.sh
[root@web1 scripts]# cat test15.sh
#!/bin/bash
if [ -f /etc/hosts ]
then
echo "[1]"
fi if [[ -f /etc/hosts ]]
then
echo "[1]"
fi if test -f /etc/hosts
then
echo "test1"
[root@web1 scripts]# ./test15.sh
[]
[]
test1

    2)开发shell脚本判断系统剩余内存的大小,如果低于3850mb,就邮件报警给系统管理员,并且讲脚本加入系统定时任务,每3分钟执行一次

    3步法则:

      1)分析需求

      2)设计思路

          获取系统剩余内存值-命令

          配置邮件报警-可用第三方邮件服务器

          判断取值是否小于100mb,如小于就报警-if

          编码实现shell脚本

          加入crond定时任务,每三分钟检查一次

      3)编码实现

         1.取内存值

[root@web1 ~]# free -m
total used free shared buff/cache available
Mem:
Swap: 3840 #<---这里取3840这个值作为可用内存
[root@web1 ~]# free -m |awk 'NR==3{print $NF}' #<---利用awk获取到3840单位时MB [root@web1 ~]#

        2.邮件设置

[root@web1 ~]# echo -e "set from=zhutoyearn@163.com smtp=smtp.163.com\nset smtp-auth-user=zhutoyearn smtp-auth-password=1qazxsw2 smtp-auth=login" >>/etc/mail.rc
[root@web1 ~]# !tail
tail - /etc/mail.rc
set from=zhutoyearn@.com smtp=smtp..com
set smtp-auth-user=zhutoyearn smtp-auth-password=xxxxxxxx smtp-auth=login
[root@web1 ~]# echo "zxg"|mail -s "title" zhutoyearn@.com

        查看邮箱是否收到邮件

       3.开始写脚本

[root@web1 scripts]# cat test16.sh
#!/bin/bash
Freemem=`free -m|awk 'NR==3 {print $NF}'`            #<---获取系统当前的内存值,赋给变量Freemem
CHARS="current memory is $freemem."                #<---定义字符串CHARS变量,作为输出及供邮件正文使用
if [ $Freemem -lt ]                       #<---判断如果小于3850,则执行命令
then
echo $CHARS|tee /tmp/messages.txt        #<---屏幕输出提示,并写入文件
mail -s "`date +%F-%T` $CHARS" zhutoyearn@.com </tmp/messages.txt #发送邮件
fi [root@web1 scripts]# chmod +x test16.sh
[root@web1 scripts]# ./test16.sh
current memory is 3840.
[root@web1 scripts]# cat /tmp/messages.txt
current memory is 3840.

      4.加入crond定时任务

no crontab for root
[root@web1 scripts]# vim /etc/crontab SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root # For details see man crontabs # Example of job definition:
# .---------------- minute ( - )
# | .------------- hour ( - )
# | | .---------- day of month ( - )
# | | | .------- month ( - ) OR jan,feb,mar,apr ...
# | | | | .---- day of week ( - ) (Sunday= or ) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
#monitor sys mem at by zxg
*/3 * * * * root /scripts/test16.sh &>/dev/null
~
~
[root@web1 scripts]# crontab /etc/crontab      #保存使其生效
[root@web1 scripts]# crontab -l
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root # For details see man crontabs # Example of job definition:
# .---------------- minute ( - )
# | .------------- hour ( - )
# | | .---------- day of month ( - )
# | | | .------- month ( - ) OR jan,feb,mar,apr ...
# | | | | .---- day of week ( - ) (Sunday= or ) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
#monitor sys mem at by zxg
*/ * * * * root /scripts/test16.sh &>/dev/null
[root@web1 scripts]#

      进入邮箱验证一下,没有问题

  2、深入if语句(多分支)

    1)分别使用read读入及脚本传参的方式比较两个整数的大小

      方法1 read读入单分支

[root@web1 scripts]# cat test17.sh
#!/bin/bash
read -p "pls input two num:" a b       #<---读入两个输入,分别复制给变量a和b
if [ $a -lt $b ];then             #<---如果$a小于$b,则执行命令
echo "yes,$a less than $b"      #<---打印输出,提醒用户
exit 0                 #<---判断完毕,成功执行,以0值退出脚本,此处如果不退出,则会继续执行下面的if语句,而这时不必要的
fi
if [ $a -eq $b ];then             #<---如果$a等于$b,则执行命令,同理,成功后以0退出脚本
echo "yes,$a equal $b"        
exit
fi
if [ $a -gt $b ];then             #<--如果$a大于$b,则执行命令,同理,成功后以0值退出脚本
echo "yes,$a greater than $b"
exit
fi
[root@web1 scripts]# chmod +x test17.sh
[root@web1 scripts]# ./test17.sh
pls input two num:
yes, less than
[root@web1 scripts]# ./test17.sh
pls input two num:
yes, greater than
[root@web1 scripts]# ./test17.sh
pls input two num:
yes, equal
[root@web1 scripts]#

      方法2,上面方法语法比较乱要写很多if,可以用多分枝语句如下:

[root@web1 scripts]# cat test18.sh
#!/bin/bash
read -p "pls input two num:" a b
if [ $a -lt $b ];then
echo "yes,$a less than $b"
elif [ $a -eq $b ];then
echo "yes,$a equal $b"
else [ $a -gt $b ]
echo "yes,$a greater than $b"
fi
[root@web1 scripts]# chmod +x test18.sh
[root@web1 scripts]# ./test18.sh
pls input two num:
yes, equal 2
[root@web1 scripts]# ./test18.sh
pls input two num:
yes, less than
[root@web1 scripts]# ./test18.sh
pls input two num:
yes, greater than

      方法3 用脚本传参的方式比较整数大小(单分支)

[root@web1 scripts]# cat test19.sh
#!/bin/bash
a=$
b=$
if [ $a -lt $b ];then
echo "yes,$a less than $b"
exit
fi
if [ $a -eq $b ];then
echo "yes,$a equal $b"
exit
fi
if [ $a -gt $b ];then
echo "yes,$a greater than $b"
exit
fi [root@web1 scripts]# chmod +x test19.sh
[root@web1 scripts]# ./test19.sh
yes, less than
[root@web1 scripts]# ./test19.sh
yes, less than
[root@web1 scripts]# ./test19.sh
yes, equal
[root@web1 scripts]# ./test19.sh
yes, greater than
[root@web1 scripts]#

       方法4 用脚本传参的方式比较整数大小(多分支)

[root@web1 scripts]# cat test20.sh
#!/bin/bash
a=$
b=$
if [ $a -lt $b ];then
echo "yes,$a less than $b"
elif [ $a -eq $b ];then
echo "yes,$a equal $b"
else [ $a -gt $b ]
echo "yes,$a greater than $b"
fi
[root@web1 scripts]# ./test20.sh
yes, equal
[root@web1 scripts]# ./test20.sh
yes, greater than
[root@web1 scripts]# ./test20.sh
yes, less than
[root@web1 scripts]#

转载请注明出处:https://www.cnblogs.com/zhangxingeng/p/11158122.html

 

shell 学习笔记5-shell-if语句的更多相关文章

  1. Shell学习笔记之shell脚本和python脚本实现批量ping IP测试

    0x00 将IP列表放到txt文件内 先建一个存放ip列表的txt文件: [root@yysslopenvpn01 ~]# cat hostip.txt 192.168.130.1 192.168.1 ...

  2. shell 学习笔记9-while/until循环语句

    一.while循环语句 1.循环语句 循环愈久就是重复执行一条指令或一组执行,知道条件不在满足时停止,shell循环语句包括,while.until.for.select语句 2.while循环 主要 ...

  3. 鸟书shell 学习笔记(一) shell专注于概念和命令

    变量   variableName=value 等号左右不能有空格 变量内容有空格须要用"或者'括起来,可是 v="hello $name" $保持原有功能,单引號则不行 ...

  4. shell学习笔记2: shell中的四则运算符

    shell中的四则运算符 n1,n2 :常量数字 char:运算符号 加,减,乘,除,取余(+,-,*,/,%) $a,$b:变量a,变量b 方法1 数字与符号之间需要有空格 不支持小数 expr n ...

  5. shell学习笔记1: shell 中的变量与常见符号使用方法

    变量 声明即用 a=2 b="123" 调用 ${varName}或者 $varName echo $b echo ${a} 常见变量 $?:判断上一个语句是否成功 $0:执行脚本 ...

  6. 鸟书shell 学习笔记(二) shell中正則表達式相关

    通配符与正則表達式的差别 通配符是bash原生支持的语法,正則表達式是处理字符串的一种表示方式, 正則表達式须要支持的工具支持才干够 语系设置 : export LANG=C grep alias 设 ...

  7. shell学习笔记汇总

    1.shell脚本中函数使用 函数定义在前,调用在后,顺序反了就没有效果了.函数调用为:函数名 参数列表 函数内部通过以下变量访问函数的参数:shell脚本函数中: $0: 这个脚本的名字 $n: 这 ...

  8. SHELL学习笔记三

    SHELL学习笔记一 SHELL学习笔记二 SHELL学习笔记三 for 命令 读取列表中的复杂值 从变量读取列表 从命令读取值 更改字段分隔符 用通配符读取目录 which 使用多个测试命令 unt ...

  9. shell学习笔记

    shell学习笔记 .查看/etc/shells,看看有几个可用的Shell . 曾经用过的命令存在.bash_history中,但是~/.bash_history记录的是前一次登录前记录的所有指令, ...

  10. [转帖][Bash Shell] Shell学习笔记

    [Bash Shell] Shell学习笔记 http://www.cnblogs.com/maybe2030/p/5022595.html  阅读目录 编译型语言 解释型语言 5.1 作为可执行程序 ...

随机推荐

  1. 查看mysql事务的隔离级别

    1.选择数据库,查看当前事务隔离界别 select @@tx_isolation; 2.开启事务,回滚事务 3.事务级别中脏读,幻读 4.MySQL事务autocommit设置,每次sql必须用com ...

  2. keep-alive 实现从列表页到详情页,然后再回到列表页并保持原来列表页的页码数,并且只刷新数据

    思路: keep-alive应用场景介绍 <keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例.结合router,缓存部分页面 activated 和 deactiv ...

  3. 《浅谈F5健康检查常用的几种方式》—那些你应该知道的知识(二)

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/sinat_17736151/articl ...

  4. 005 Spring和SpringBoot中的@Component 和@ComponentScan注解

    今天在看@ComponentScan,感觉不是太理解,下面做一个说明. 1.说明 ComponentScan做的事情就是告诉Spring从哪里找到bean 2.细节说明 如果你的其他包都在使用了@Sp ...

  5. nginx奔溃自动重启Shell脚本

    # vi /usr/local/nginx/sbin/nginx_restart.sh 贴入一下代码: #!/bin/bash #www.xmsolink.com #Monitor nginx ser ...

  6. 在 ServiceModel 客户端配置部分中,找不到引用协定“WebServiceSoap”的默认终结点元素。这可能是因为未找到应用程序的配置文件,或者是因为客户端元素找不到与此协定匹配的终结点元素(转)

    按语: 在项目中实现自动升级过程,在类库中调用webservice取升级update.xml文件,添加服务调用,但在类库中调用时就出现异常,但在简单的测试工程中没有问题.解决方法采用下面介绍的方法 在 ...

  7. PhpStorm的主题和字体设置

    打开PhpStorm,点击File,然后点击Setting 然后 点击Apply,就可以看到主题变化的效果,其次就是来设置字体,先要选取一个样式,然后点击Save As ,然后命名,我选择的是最后一个 ...

  8. DB2使用MERGE INTO语句实现西虹市首富的新增及更新操作

    首先我们新建一张名为XIHONGSHISHOUFU的表,这张表是评委会初步评选出的西虹市首富的候选人员,下面的SQL语句包含建表和插入数据的部分: CREATE TABLE XIHONGSHISHOU ...

  9. 微信小程序,内容组件中兼容的H5组件

    受信任的HTML节点及属性 全局支持class和style属性,不支持id属性. 节点 属性 a   abbr   address   article   aside   b   bdi   bdo ...

  10. npm i node-sass 报错&npm 镜像切换

    npm install --save node-sass --registry=https://registry.npm.taobao.org --disturl=https://npm.taobao ...