if-then中的test命令

此处只是做记录使用

1、数值比较

比  较		        描  述
n1 -eq n2 		检查n1是否与n2相等
n1 -ge n2 		检查n1是否大于或等于n2
n1 -gt n2 		检查n1是否大于n2
n1 -le n2 		检查n1是否小于或等于n2
n1 -lt n2 		检查n1是否小于n2
n1 -ne n2 		检查n1是否不等于n2

例如:

# cat numeric_test.sh 
#!/bin/bash
# Using numeric test evaluations
#
value1=10
value2=11
#
if [ $value1 -gt 5 ]
then 
    echo "The test value $value1 is greater than 5"
fi
#
if [ $value1 -eq $value2 ]
then 
    echo "The values are equal"
else
    echo "The valuses are different"
fi

 

2、字符串比较测试

比  较			描  述
str1 = str2 	        检查str1是否和str2相同
str1 != str2 	        检查str1是否和str2不同
str1 < str2 	        检查str1是否比str2小
str1 > str2 	        检查str1是否比str2大
-n str1 		检查str1的长度是否非0
-z str1 		检查str1的长度是否为0

例如:

# cat teststring.sh
#!/bin/bash
# testing string equality
testuser=rich
#
if [ $USER = $testuser ]
then
echo "Welcome $testuser"
fi

当使用大于或者小于号进行比较时需要添加转义符,否则脚本会认为是重定向命令,正常执行重定向返回退出状态码也是0,所以会正常输出then部分的内容。所以用><时需要加\进行转意。

3、文件比较

比  较				描  述
-d file 			检查file是否存在并是一个目录
-e file 			检查file是否存在
-f file 			检查file是否存在并是一个文件
-r file 			检查file是否存在并可读
-s file 			检查file是否存在并非空
-w file 			检查file是否存在并可写
-x file 			检查file是否存在并可执行
-O file 			检查file是否存在并属当前用户所有
-G file 			检查file是否存在并且默认组与当前用户相同
file1 -nt file2 	        检查file1是否比file2新
file1 -ot file2 	        检查file1是否比file2旧

例如,检查目录:

$ cat test11.sh
#!/bin/bash
# Look before you leap
#
jump_directory=/home/test
#
if [ -d $jump_directory ]
then
echo "The $jump_directory directory exists"
cd $jump_directory
ls
else
echo "The $jump_directory directory does not exist"
fi