Linux Shell 04 数字/字符串/文件测试

一. 数字测试

  格式:n1  -op  n2

  测试操作op:

    eq/ne/le/ge/lt/gt    -->    等于/不等于/小于等于/大于等于/小于/大于

  1. 数字比较可以使用特殊的(())操作符,用法更接近于C语言,见数字测试

二. 字符串测试

  s1 = s2    #s1与s2是否相同

  s1 != s2    #s1与s2是否不相同

  s1 < s2    #s1是否小于s2

  s1 > s2    #s1是否大于s2

  -n s1     #s1长度是否大于0

  -z s1      #s1长度是否为0

1. 字符串比较的时候大于小于符号"<>"需要转义

if [ $s1 > $s2]
then
    echo "$s1 is  greater than $s2"
else
    echo "$s2 is  greater than $s1"
fi

2. 字符串大小比较使用字符的ASCII码值比较,即大写字母小于小写字母。(而sort命令的排序方式恰好相反)

3. 未定义的变量字符串长度为0

三. 文件测试

  格式: f1 -nt f2    f1是否比f2新

      f1 -ot f2    f1是否比f2旧

      -op file

  op操作符:

    e/d/f/r/w/x/s/L/O/G   -->   是否 存在/目录/文件/可读/可写/可执行/存在且不为空/符号链接/当前用户拥有/当前组拥有

  1.比较文件的新旧时按照创建时间比较的,且要求两个文件都存在,否则返回失败条件

if [ -G $HOME/test ]
then
      echo "You are in the same group as the file"
else
      echo "The file is not owned by your group"
fi
原文地址:https://www.cnblogs.com/techroad4ca/p/5440952.html