Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。
数值测试
符号含义:
1. eq (equal的缩写),表示等于为真
2. ne (not equal的缩写),表示不等于为真
3. gt (greater than的缩写),表示大于为真
4. ge (greater&equal的缩写),表示大于等于为真
5. lt (lower than的缩写),表示小于为真
6. le (lower&equal的缩写),表示小于等于为真
例子:
num1=100
num2=100
if test $[num1] -eq $[num2] #test的作用就是代替了[ ]
then
echo '两个数相等!'
else
echo '两个数不相等!'
fi
输出结果:
两个数相等!
代码中的 [ ] 可以执行基本的算数运算,如:
#!/bin/bash
a=5
b=6
result=$[a+b] # 注意等号两边不能有空格
echo "result 为: $result"
结果为:
result 为: 11
字符串测试
num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
echo '两个字符串相等!'
else
echo '两个字符串不相等!'
fi
输出结果:
两个字符串不相等!
文件测试
if test -e ./bash
then
echo '文件已存在!'
else
echo '文件不存在!'
fi
输出结果:
文件已存在!