zoukankan      html  css  js  c++  java
  • shell入门之变量测试 分类: 学习笔记 linux ubuntu 2015-07-10 15:49 31人阅读 评论(0) 收藏


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

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

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

  • 相关阅读:
    Tomcat的安装配置与JavaWeb入门教程
    傅立叶变换系列(一)傅立叶系列的由来
    剑指Offer(四):重建二叉树
    《C++数据结构-快速拾遗》 手写链表
    《C++数据结构-快速拾遗》 基础常识
    《机器学习实战》线性回归
    剑指Offer(三):从尾到头打印链表
    博客美化操作
    偏差、方差和噪声的权衡关系
    《机器学习实战》AdaBoost算法(手稿+代码)
  • 原文地址:https://www.cnblogs.com/lenve/p/4637540.html
Copyright © 2011-2022 走看看