linux bash中 test命令详解

test命令用于检查某个条件是否成立。它可以进行数值、字符和文件三方面的测试。

1、数值测试

  • -eq 等于
  • -ne 不等于
  • -gt 大于
  • -ge 大于或等于
  • -lt 小于
  • -le 小于或等于

例如,我们可以测试两个变量是否相等:

num1=100
num2=200
if test $num1 -eq $num2
then
    echo 'Two values are equal!'
else
    echo 'Two values are not equal!'
fi

2、字符串测试

  • = 等于
  • != 不等于
  • -z 字符串长度是否为0,长度为0返回真
  • -n 字符串长度是否为0,长度不为0返回真

例如,我们可以测试两个字符串是否相同:

str1="hello"
str2="world"
if test str1 = str2
then
    echo 'Two strings are the same!'
else
    echo 'Two strings are different!'
fi

3、文件测试

  • -e 文件是否存在
  • -d 是否存在并且是一个目录
  • -f 是否存在并且是一个文件
  • -r 文件是否存在并且可读
  • -w 文件是否存在并且可写
  • -x 文件是否存在并且可执行

例如,我们可以测试文件是否存在并且是一个目录:

dir_path="./my_dir"
if test -d $dir_path
then
    echo 'The directory exists!'
else
    echo 'The directory does not exist!'
fi

注意: [test 的简化版本,所以下面两种写法是等价的:

if test $a -eq $b if [ $a -eq $b ]

猜你喜欢

转载自blog.csdn.net/jkzyx123/article/details/132716297