Shell编程-06-Shell中的if语句

    在任何一门语言中,判断语句总是少不了,今天来学习一下Shell中的if语句。

基本语法

单分支情况
  • 第一种语法
if <条件表达式>
   then
     语句
fi
  • 第二种语法
if <条件表达式>;then
     语句
fi

其中条件表达式部分可以是test、[]、[[]]和(())等条件表达式。以上两种格式,可根据自己实际情况选择一种即可。

双分支情况
if <条件表达式>
  then
    语句
else
   语句
fi
多分支情况
if <条件表达式>
  then
    语句
elif  <条件表达式>
  then
    语句
elif  <条件表达式>
  then
    语句
else
   语句
fi

在多分支的if中,每个elif中后均需要带有then

分支嵌套情况
if <条件表达式>
  then
    if <条件表达式>
      then
       语句
    fi
fi

在以上的写法注意缩进,方便阅读
建议在一个if嵌套不要超过三层

if与条件表达式语法

    在前面讲过各个条件测试表达式,如test、[]、[[]]和(())等条件表达式,如下所示:

  • 1、test表达式
if test <表达式>
  then
    语句
fi
  • 2、[]表达式
if [ <表达式> ]
  then
    语句
fi
  • 3、[ [ ] ]表达式
if [[ <表达式> ]]
  then
    语句
fi
  • 4、(( ))表达式
if (( <表达式> ))
  then
    语句
fi
  • 5、命令表达式
if 命令
  then
    语句
fi

if示例

1、if示例:判断文件是否且为普通文件

[root@localhost ~]# [ -f /etc/passwd ] && echo true || echo false
true
[root@localhost ~]# test -f /etc/passwd && echo true || echo false
true

与以下写法等效

[root@localhost Test]# cat if.sh
#!/bin/bash
if [ -f "$1" ]
  then
    echo true
else
  echo false
fi

if test -f "$2"
  then
    echo true
else
  echo false
fi
[root@localhost Test]# bash if.sh /etc/passwd /etc/hostssss
true
false

2、if示例:比较输入数字的大小

[root@localhost Test]# cat compareNum.sh
#!/bin/bash
a=$1
b=$2
echo "Inputed number is:" ${a} ${b}

if [ $# -ne 2 ]
  then
    echo "input number must be 2 number."
    exit 2
fi

expr $a + 2 &> /dev/null # 检查是否为整数
resulta=$?
expr $b + 2 &> /dev/null # 检查是否为整数
resultb=$?

if [ $resulta -eq 0 -a $resultb -eq 0 ] # 判断检查结果
    then
    if [ $a -gt $b ]
        then
            echo "$a > $b"
    elif [ $a -lt $b ]
       then
            echo "$a < $b"
    elif [ $a -eq $b ]
          then
           echo "$a = $b"
       else
         echo "error"
       fi
else
   echo "please check your input"
fi

[root@localhost Test]# bash compareNum.sh 1 # 输入一个数字
Inputed number is: 1
input number must be 2 number.

[root@localhost Test]# bash compareNum.sh a b  # 输入字母
Inputed number is: a b
please check your input

[root@localhost Test]# bash compareNum.sh 900 89 # 输入两个数字
Inputed number is: 900 89
900 > 89

[root@localhost Test]# bash compareNum.sh 89 900
Inputed number is: 89 900
89 < 900

[root@localhost Test]# bash compareNum.sh 900 900
Inputed number is: 900 900
900 = 900

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:
MyQRCode.jpg

转载于:https://www.cnblogs.com/surpassme/p/9966244.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值