Linux shell入门之变量测试

格式:test 测试条件

字符串测试:

注意空格:
test str1 == str2 测试字符串是否相等
test str1 != str2 测试字符串是否不相等
test str1 测试字符串是否不为空
test -n str1 测试字符串是否不为空
test -z str1 测试字符串是否为空

整数测试
test int1 -eq int2 测试整数是否相等
test int1 -ge int2 测试int1是否>=int2
test int1 -gt int2 测试int1是否>int2
test int1 -le int2 测试int1是否<=int2
test int1 -lt int2 测试int1是否<int2
test int1 -ne int2 测试两个数是否不相等

文件测试
test -d file 指定文件是否为目录
test -f file 指定文件是否为常规文件
test -x file 指定文件是否可执行
test -r file 指定文件是否可读
test -w file 指定文件是否可写
test -a file 指定文件是否存在
test -s file 指定文件大小是否非0


测试语句一般不单独使用,一般作为if语句的测试条件,如:

if test "hello" == "hello" ;then
commands....
fi

上面语句也可简化为(注意[]与"之间的空格)
if [ "hello" == "hello" ];then
....

看一段代码:

#!/bin/bash
if test "hello" == "hello" ;then
echo "equals"
else
echo "not equals"
fi
if test -z "" ;then
echo "str is null"
fi
if test -n "" ;then
echo "str is not null"
fi
if test "9" ;then
echo "not null"
else
echo "null"
fi
#easy way
if [ "hello" == "hello" ];then
echo "equals"
else
echo "not equals"
fi
if [ -f /root/test/test1 ];then
echo "test1 is a file"
elif [ -d /root/test/test1 ];then
echo "test1 is a dir"
else
echo "i don't know the result"
fi

执行效果:
这里写图片描述

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/121391.htm
今日推荐