Shell编程-08-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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 9,668评论 0 13
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,960评论 1 45
  • 文/无悔 专注之心,可以成事, 专注之力,可以无敌。 任世间纷杂, 心静如水。 ——20...
    无悔随笔阅读 2,934评论 1 1
  • 只此一世,遇见,偕老 不问前世,不盼来生 可好?...
    鹏先生的私论坊阅读 1,176评论 0 0
  • 长夏以来,天气的燥热让人心烦。 每日按部就班的生活,在班车上体会烈日的灼烤,靠在班车座椅上,默念心静自然凉的咒语,...
    Araybellar阅读 3,449评论 2 2