Linux Shell脚本if-else语句及test命令

Linux中的if语句根据其后紧跟的command语句的退出码是否非零进行逻辑判断,这是不同于其他编程语言的一个特性。

状态退出码的介绍可以参考:https://www.jianshu.com/p/ba478a2dbcbc

if-then语句的基本格式

if command

then

    commands

fi

抑或是:

if command; then

commands

fi

请注意后者在待求值的命令尾部增加了分号

if-then-else语句的基本格式

if command

then 

    commands

else

    commands

fi

需要多个if判断逻辑时使用如下命令

if command1

then

    commands set 1

elif command2

then

    commands set 2

else 

    commands set 3

fi

test命令

在if-then语句中需要以命令是否成立作为判断条件时用test命令来辅助。

语法:

1.test condition

test命令中的条件成立,test命令将退出并返回状态码0,反之,退出返回非零状态码。

当test命令中的语句为空时,会判定为语句不成立,退出并返回非零状态码。

2.[ condition ]

bash shell 提供了另一种测试方法,也就是test命令的另一种语法。

在if-then语句中将是这样的形态:

if [ condition ]

then 

    commands

fi


test命令可以判断的三类条件

□数值比较

□字符串比较

□文件比较

数值比较

    符 号                描述

  n1 -eq n2        n1与n2是否相等

  n1 -ge n2        n1是否大于或等于n2

  n1 -gt n2         n1是否大于n2

  n1 -le n2         n1是否小于或等于n2

  n1 -lt n2          n1是否小于n2

  n1 -ne n2        n1是否不等于n2

这里能处理的是整数和变量:

#!/bin/bash

value1=10

if [ $value1 -gt 5 ]

then

   echo "The test value $value1 is greater than 5"

else

   echo "The test value $value1 is smaller than 5"

不能处理浮点数。

字符串比较

    符 号                描述

  str1 = str2        str1是否与str2相同

  str1 != str2        str1是否与str2不同

  str1 < str2         str1是否比str2小

  str1 > str2         str1是否比str2大

    -n str1             str1长度是否非零

    -z str1             str1长度是否为0


文件比较

符号 描述

-d file      file是否为一个目录

-e file      file是否存在

-f file      file是否存在并是一个文件

-r file      file是否存在并可读

-s file      file是否存在并非空

-w file      file是否存在并可写

-x file      file是否存在并可执行

-O file      file是否存在并属当前用户所有

-G file      file是否存在并且默认组与当前用户相同

file1 -nt file1  file1是否比file2新

file1 -ot file1  file1是否比file2旧    #这里的新旧依据是文件的创建时间

欢迎指正和补充。

你可能感兴趣的:(Linux Shell脚本if-else语句及test命令)