手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux shell入门之变量测试

[日期:2015-08-09] 来源:Linux社区  作者:Linux [字体:大 中 小]

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

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

Linux Shell在while中用read从键盘输入  http://www.linuxidc.com/Linux/2015-06/118831.htm

Linux Shell 程序调试  http://www.linuxidc.com/Linux/2015-07/119880.htm

Linux Shell脚本面试25问  http://www.linuxidc.com/Linux/2015-04/116474.htm

Linux/Unix Shell 参数传递到SQL脚本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell脚本中参数传递方法介绍 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell脚本传递命令行参数 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、转义字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm 

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/121391.htm

linux
相关资讯       Linux Shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款