条件测试语句
1、在写shell脚本时,经常遇到的问题就是判断字符串是否相等,可能还要检查文件状态或进行数字测试,只有这些测试完成才能做下一步动作。
(1)test命令:用于测试字符串、文件状态和数字。
test命令有两种格式:
格式:test condition 或[ condition ]
注意:使用方括号时,要注意在条件两边加上空格
(2)shell脚本中的条件测试如下:
文件测试、字符串测试、数字测试、复合测试。
测试语句一般与后面讲的条件语句联合使用。
2、文件测试:测试文件状态的条件表达式
-e 是否存在 -d 是目录 -f 是文件
-r 可读 -w 可写 -x 可执行
-L 符号连接 -c是否字符设备 -b是否块设备
-s 文件非空
例:6_test_file.sh
#!/bin/bash
test -e /dev/qaz
echo $?
test -e /home
echo $?
test -d /home
echo $?
test -f /home
echo $?
mkdir test_sh
chmod 500 test_sh
[ -r test_sh ]
echo $?
[ -w test_sh ]
echo $?
[ -x test_sh ]
echo $?
[ -s test_sh ]
echo $?
[ -c /dev/console ]
echo $?
[ -b /dev/sda ]
echo $?
[ -L /dev/stdin ]
echo $?
3、字符串测试
test str_operator “str”
test “str1” str_operator “str2”
[ str_operator “str” ]
[ “str1” str_operator “str2”]
注意:其中str_operator可以是:
= 两个字符串相等 != 两个字符串不相等
-z 空串 -n 非空串
例:7_test_string.sh
#!/bin/bash
test -z $yn
echo $?
echo "please input a y/n"
read yn
[ -z "$yn" ]
echo 1:$?
[ $yn = "y" ]
echo 2:$?
4、测试数值格式如下:
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
例:8_test_num.sh
#!/bin/bash
echo "please input a num(1-9)"
read num
[ $num -eq 5 ]
echo $?
[ $num -ne 5 ]
echo $?
[ $num -gt 5 ]
echo $?
[ $num -ge 5 ]
echo $?
[ $num -le 5 ]
echo $?
[ $num -lt 5 ]
echo $?
5、复合测试
命令执行控制:
&&:
command1 && command2
&&左边命令(command1)执行成功(即返回0)shell才执行&&右边的命令(command2)
||
command1 || command2
||左边的命令(command1)未执行成功(即返回非0)shell才执行||右边的命令(command2)
例:9_test_fuhe.sh
test -e /home && test -d /home && echo "true"
test 2 -lt 3 && test 5 -gt 3 && echo "equal"
test "aaa" = "aaa" || echo "not equal" && echo "equal"