条件测试语句 test:用于测试字符串、文件状态和数字,其有两种书写格式:test condition 和 [ condision ](注意condision两端的空格)
1、测试文件是否存在
携带参数 | |||
-e 是否存在 | -d 是目录 | -f 是文件 | -r 可读 |
-w 可写 | -x 可执行 | -L 符号连接 | -c 是否字符设备 |
-b 是否块设备 | -s 文件非空 |
示例:假设输入文件路径存在
#!/bin/bash
read -p "请输入一个文件名: " filename
test -e $filename
echo $?
[ -e $fliename ]
echo $?
运行结果:
xxx@PC:~$ ./first.sh 请输入一个文件名: xxx 0 0 xxx@PC:~$ |
2、字符串测试
test "str1" str_operator "str2" 或 [ "str1" str_operator "str2" ]
其中,str_operator 可以是以下四类:
= 两个字符串相等 | !=两个字符串不相等 |
-z 空串 | -n 非空串 |
3、数值测试
test num1 num_operator num2 或 [ num1 num_operator num2 ]
其中,num_operator 可以是以下六类:
-eq 数值相等 | -ne 数值不想等 | -gt 数1大于数2 |
-ge 数1大于等于数2 | -le 数1小于等于数2 | -lt 数1小于数2 |
4、复合语句测试
命令执行控制语句:
1、command1 && command2 当command1执行成功后,才可以执行command2
2、command1 || command2 当command1执行失败后,才可以执行command2
多重条件判定语句:
-a | (and)两种情况同时成立,例:test -r file -a -x file,同时具有读和执行的权限 |
-o | (or)两种情况有一个及以上成立,例:test -r file -o -x file,具有其中一个及以上权限 |
! | 相反状态,例:test !-x file,当file不具有x时成立 |