一.概述

  在上一篇里讲到了shell脚本,shell按照命令在脚本中出现的顺序依次进行处理,对于顺序操作已经足够了,但许多程序要求对shell脚本中的命令加入一些逻辑流程控制,这样的命令通常叫做 结构化命令。

  1.1 使用if - then语句

--最基本的结构化就是if -then语句,格式如下:
     if command
     then
        commands
     fi

  在其他编程语言中,if是一个等式,值结果为ture或false,但在bash shell的if语句并不是这样。在bash shell的if语句会运行if后面的那个命令,如果该命令的退出状态码是0,位于then部分的命令就会被执行。反之则不执行,继续执行脚本中的下一个命令。 fi 语句用来表示if -then语句到此结束。下面是一个if -then简单例子如下:
    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP
  上面脚本在if行采用了pwd命令,命令成功结束,echo语句显示了文本字符串。

  使用if 执行多个命令时,bash shell会将这些命令当成一个块,如果if语句行的命令退出状态值为0, 所有命令都会被执行,如果if语句行的命令的退出状态不为0,所有的命令都会被跳过。下面一个案例if 涉及到了两个命令一个是grep $testuser,  另一个是显示路径/etc/passwd。上图示例中mysql用户存在,报以退出状态码是0。并显示了echo信息。

    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP
  下面演示如果testuser变量设置成一个系统上不存在的用户,状态码则不是返回0,不进入if then 中,什么都不会显示。
    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP

  1.2  if-then-else语句

  如果if 执行命令返回一个非零退出状态码,bash shell 会继续执行脚本中的下一条命令,这时else语句提供了作用,格式如下:

-- if -then -else格式:
if command
    then
        commands
    else
        commands
 fi

  下面示例,在原有脚本上加入else语句块,最后显示了else中的信息。

    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP

  1.3 嵌套if

  嵌套的if -then 语句位于主if -then-else语句的else代码块中。如下所示在else 语句块中再嵌入if-then-else

    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP

   对于else部分的另一种形式是: elif, 这样就不用再写多个if-then语句了,elif是另一个if-then语句延续else部分, 这种比上面的if嵌套可读性强, 同样把上面的脚本改一下,示例如下,if 命令退出状态码不为0,进入到elif语句块中。
    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP
   对于elif后面还可以加else语句块 ,当elif命令返回也不为0时,进入最后的else语句块,如下图所示:

    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP
  对于 elif语句 还可以是多个串起来。这里就不再演示, 语法如下:

if command1
then
   command set 1
elif command2
then
    ...
elif command3
then
    ...
else
   ...
fi

  对于上面的if结构化语句,归纳起来如下面四种格式, 类似于其它编辑语言的if ..else 或if  ..else if.. else。

if-then
if-then   else
if-then   elif-then  else
if-then   elif-then   elif-then     else

  1.4  结构化test命令

  上面的if 命令只能测试普通的shell命令的状态码,下面介绍test命令,它能测试不同条件, 条件成立同样是退出状态码为0, 如果条件不成立测返回非0状态码。

-- test命令格式如下
if test  condition
then
    commands
fi

  下面是使用test命令确定变量中是否有内容,下面的testuser变量值为mysql,  因此test命令返回状态码为0,进入了then语句块中。示例如下:
    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP
  下面演示变量没有值的情况下,test命令返回状态码不为0,进入了else语句块中。
    Linux编程 23 shell编程(结构化条件判断 命令if -then , if-then ... elif-then ...else,if test)-LMLPHP

  在bash shell中提供了另一种条件测试方法,无需在if -then语句中声明test命令,使用[condition] 这种应该是日常使用比较频繁的。 这种代替test的用法在下一篇中在详细解说。

--格式如下:
if  [condition]
then
    commands
fi
10-12 17:48