shell--test条件测试

条件测试在shell中用来判断条件是否为真,如果指定的条件为真时,条件测试返回值为0

可用test或[ ]测试(注意:使用[]需在左右添加格式,eg:[ word1 op word2 ])
测试完后可通过 echo $? 打印出结果

  • 字符串测试

test word1 op word2
[ word1 op word2 ]

test string 判断指定字符串是否为空
test string1 = string2 判断字符串是否相等
test string1 != string2 判断字符串是否不相等
test -n string 判断字符串是否为非空
test -z string 判断字符串是否为空
  • 整数测试

test number1 op number2
[ number1 op number2 ]

a=1
b=2
[ $a -eq $b ] 比较两个整数是否相等
[ $a -ne $b ] 比较两个整数是否不相等
[ $a -gt $b ] 比较a是否大于b
[ $a -lt $b ] 比较a是否小于b
[ $a -ge $b ] 比较a是否大于等于b
[ $a -le $b ] 比较a是否小于等于b
  • 文件测试

test op file
[ op file ]

test -a file 或test -e file 文件是否存在
test -b file 文件是否存在,且为块文件
test -c file 文件是否存在,且为字符文件
test -d file 文件是否存在,且为目录
test -s file 文件的长度是否大于0,或者为非空文件
test -f file 文件存在,且为常规文件
test -w file 文件是否存在且可写
test -r file 文件是否存在且可读
test -x file 文件是否存在且可执行
test -L file 文件是否存在,并且为符号链接
test -u file 文件是否设置suid位
  • 逻辑判断
[ ! expression ] 当条件表达式为假,该运算返回0
[ expression -a expression ] 当条件判断都为真时,该运算返回0
[ expression -o expression ] 当条件判断有一个为真时,该运算返回0
posted @ 2022-05-04 12:31  liu_kx  阅读(98)  评论(0编辑  收藏  举报