test命令
1.测试特定的表达式是否成立。条件成立时,命令执行后的返回值为0,否则返回一个大于0的值
2.test命令也被链接到方括号上。这样既可以单独使用test命令,也可以通过把表达式用方括号括起来,来测试表达式的值
test 表达式 [ 表达式 ]
3.在用test或方括号测试表达式时,表达式中的shell元字符不会被扩展,包括空白符的字符串必须用引号括起来。
eg:当name="a b"
[ -z $name ] #[ -z a b ],-z后有两个参数,而-z只需要一个参数,这时shell解释器会报错
[ -z "$name" ] #这样无论变量值是什么,shell都会把变量值看成一个整体
所以最好把变量都用“”括起来。
逻辑测试
test 表达式1 -a 表达式2 [ 表达式1 -a 表达式2 ] 操作符两边均为真则为真
test 表达式1 -o 表达式2 [ 表达式1 -o 表达式2 ] 操作符两边其中之一为真则为真
test !表达式 [ !表达式 ] !后表达式为假则为真
字符串测试
test str1 = str2 [ str1 = str2 ] 字符串相等则为真(=两侧必须有空格)
test str1 == str2 [ str1 == str2 ] 同上(2.x版bash中可以用=代替)
test str1 != str2 [ str1 != str2 ] 字符串不相等则为真
test string [ string ] string不为空则为真
test -z str [ -z str ] str的长度为0则为真
test -n str [ -n str ] str的长度不为0则为真
整数测试
test int1 -eq int2 [ int1 -eq int2 ] int1等于int2则为真
test int1 -ge int2 [ int1 -ge int2 ] int1大于或等于int2则为真
test int1 -gt int2 [ int1 -gt int2 ] int1大于int2则为真
test int1 -le int2 [ int1 -le int2 ] int1小于或等于int2则为真
test int1 -lt int2 [ int1 -lt int2 ] int1小于int2则为真
test int1 -ne int2 [ int1 -ne int2 ] 两数不等于则为真
文件测试
test file1 -ef file2 [ file1 -ef file2 ] 如果文件file1和file2有相同的设备数或i结点数则为真
test file1 -nt file2 [ file1 -nt file2 ] 如果文件file1比file2新则为真(根据修改时间)
test file1 -ot file2 [ file1 -ot file2 ] 如果文件file1比file2老则为真
test -b file [ -b file ] 块专用文件则为真
test -c file [ -c file ] 字符专用文件则为真
test -d file [ -d file ] 目录存在则为真
test -e file [ -e file ] 文件存在则为真
test -f file [ -f file ] 普通文件存在且不是目录则为真
test -g file [ -g file ] Set-group-ID被设置则为真
test -G file [ -G file ] 文件存在且属于有效组ID时则为真
test -k file [ -k file ] sticky位被设置则为真
test -L file [ -L file ] 文件是一个符号链接则为真
test -p file [ -p file ] 文件是一个命名管道则为真
test -O file [ -O file ] 文件存在且属于有效用户ID则为真
test -r file [ -r file ] 文件可读则为真
test -s file [ -s file ] 文件大小非0则为真
test -S file [ -S file ] 文件是一个socket则为真
test -t fd [ -t fd ] 如果fd(文件描述符)被一个终端打开则为真
test -u file [ -u file ] Set-user-ID位被设置则为真
test -w file [ -w file ] 文件可写则为真
test -x file [ -x file ] 文件可执行则为真