shell结构化命令if-then-elif-fi

在编写shell中,很少有脚本是顺序操作,大部分的时候需要进行逻辑判断。
先看一个简单的格式:

if command
then
    commands
fi

bash shell会运行if后面的命令。如果该命令的退出状态码是0,then后的命令就会执行。否则不执行。来个简单的例子:

#!/bin/sh
workPath=/Users/liguosong/work/shell
if cd $workPath
then
     echo Ok
fi

如果这个路径存在,就会输出Ok。

上面是一个很单间的if语句。其它语言都会有else,else if语句。shell也有。如果if后面的命令执行结果是非零,就会执行else部分。先来一个简单的else的例子:

#!/bin/sh
workPath=/Users/liguosong/work/shell
if cd $workPath
then
    echo Ok
else
    echo Path not exist.
fi

有时候需要进行多种条件判断,shell中我们可以用elif。基本的结构:

if command
then
    commands
elif command2
then
    commands
fi

上面的结构,只是普通的shell命令,if的条件是否成立都是与状态码有关的。那么把其它条件作为if判断的依据,那么我们就要学习下面的test命令了。

shell test命令

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>