shell入门之变量测试 分类: 学习笔记 linu...


格式: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

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/lenve/p/4637540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值