Shell脚本中if语句的使用方法

466 阅读2分钟

在Shell脚本中,if语句是用来进行条件判断的关键字,它的基本语法如下所示:

if [ condition ]
then
    commands
fi

其中,condition 表示要进行判断的条件,可以是变量、字符串、数字等;commands 表示如果条件成立,要执行的代码块。需要注意的是,iffi 都是 Shell 关键字,必须用空格和换行符进行分隔。

除了基本的if语句外,还有其他几种if语句的使用方法,具体如下:

if-else语句

if-else语句可以根据条件的成立与否,分别执行不同的代码块,基本语法如下所示:

if [ condition ]
then
    commands1
else
    commands2
fi

如果 condition 成立,则执行 commands1,否则执行 commands2

if-elif-else语句

if-elif-else语句可以根据多个条件的成立与否,执行不同的代码块,基本语法如下所示:

if [ condition1 ]
then
    commands1
elif [ condition2 ]
then
    commands2
else
    commands3
fi

如果 condition1 成立,则执行 commands1,否则判断 condition2 是否成立,如果成立则执行 commands2,否则执行 commands3

if语句的嵌套

在Shell脚本中,if语句还可以进行嵌套,以实现更为复杂的条件判断,基本语法如下所示:

if [ condition1 ]
then
    if [ condition2 ]
    then
        commands1
    else
        commands2
    fi
else
    commands3
fi

如果 condition1 成立,则判断 condition2 是否成立,如果成立则执行 commands1,否则执行 commands2;如果 condition1 不成立,则执行 commands3

测试字符串

在Shell脚本中,if语句还可以用于测试字符串,具体如下所示:

  • string 是否为空:if [ -z string ]
  • string 是否不为空:if [ -n string ]
  • string1 是否等于 string2if [ string1 = string2 ]
  • string1 是否不等于 string2if [ string1 != string2 ]
  • string1 是否小于 string2if [[ string1 < string2 ]]
  • string1 是否大于 string2if [[ string1 > string2 ]]

需要注意的是,=!= 是 Shell 的关键字,必须用空格进行分隔;而 <> 则需要使用双括号进行括起来。

测试整数

在Shell脚本中,if语句还可以用于测试整数,具体如下所示:

  • n1 是否等于 n2if [ n1 -eq n2 ]
  • n1 是否不等于 n2if [ n1 -ne n2 ]
  • n1 是否大于 n2if [ n1 -gt n2 ]
  • n1 是否小于 n2if [ n1 -lt n2 ]
  • n1 是否大于等于 n2if [ n1 -ge n2 ]
  • n1 是否小于等于 n2if [ n1 -le n2 ]

需要注意的是,-eq-ne-gt-lt-ge-le 都是 Shell 的关键字,必须用空格进行分隔。

测试文件

在Shell脚本中,if语句还可以用于测试文件,具体如下所示:

  • file 是否存在:if [ -e file ]
  • file 是否为目录:if [ -d file ]
  • file 是否为普通文件:if [ -f file ]
  • file 是否可读:if [ -r file ]
  • file 是否可写:if [ -w file ]
  • file 是否可执行:if [ -x file ]

需要注意的是,这些测试文件的关键字都是以 - 开头的。

总结

以上就是Shell脚本中if语句的所有使用方法,通过掌握这些知识,可以帮助我们更好地进行条件判断,从而实现更为复杂的脚本功能。