zoukankan      html  css  js  c++  java
  • test 命令

    Shell test 命令

    每一种合理完整的编程语言都可以测试一个条件,然后根据测试的结果进行操作。Bash有test命令、各种括号和圆括号操作符以及if/then构造。

    与test命令相关的命令和符号:

    • If/then条件判断。
    • 内置的[]中括号和[[]双中括号,[[]]比[]更灵活和强大,可以说是增强版。
    • (())和let,一般用于算术表达式和计算比较。
    [root@localhost shell]# type test
    test is a shell builtin
    [root@localhost shell]# type [
    [ is a shell builtin
    [root@localhost shell]# type [[
    [[ is a shell keyword
    [root@localhost shell]# type let
    let is a shell builtin

    If/then可以测试任何命令,而不仅仅是括号内的条件

    #!/bin/bash
    if cmp a.txt b.txt &> /dev/null
    then
        echo 'Files a and b are identical.'
    else
        echo 'Files a and b are diff.'
    fi

    if/then测试条件格式一:

    if [ condition-true ]
    then
       command 1
       command 2
       ...
    else  # Or elif ...
          # Adds default code block executing if original condition tests false.
       command 3
       command 4
       ...
    Fi

    if/then测试条件格式二:

    if [ condition1 ]
    then
       command1
       command2
       command3
    elif [ condition2 ]
    # Same as else if
    then
       command4
       command5
    else
       default-command
    fi
     
    
     

    使用(())进行算术测试

    #!/bin/bash
    var1=7
    var2=10
    
    if (( var1 > var2 )) # not $var1 $var2, but is ok.
    then
        echo "var1 is greater than var2"
    else
        echo "var1 is less than var2"
    fi
    exit 0

    数值比较

    比较

    描述

    n1 -eq n2

    检查n1是否与n2相等

    n1 -ge n2

    检查n1是否大于或等于n2

    n1 -gt n2

    检查n1是否等于n2

    n1 -le n2

    检查n1是否小于或大于n2

    n1 -lt n2

    检查n1是否小于n2

    n1 -ne n2

    检查n1是否不等于n2

    #!/bin/bash
    
    num1=6
    num2=9
    if [ $num1 -ne $num2 ]
    then
        echo "$num1 is not equal to $num2"
    fi

    字符串比较

    参数

    说明

    Str1 = str2

    检查str1是否和str2相同

    Str1 != str2

    检查str1是否和str2不同

    -z str1

    检查str1是否为零

    -n str1

    检查str1是否非零

    Str1 > str2

    检查str1是否大于syr2

    Str1 < str2

    检查str1是否小于str2

    文件比较

    比较

    说明

    -e file

    检查file是否存在

    -r file

    检查file是否存在并可读

    -w file

    检查file是否存在并可写

    -x file

    检查file是否存在并可执行

    -s file

    检查file是否存在并非空

    -d file

    检查file是否存在并是一个目录

    -f file

    检查file是否存在并是一个文件

    -c file

    检查file是否字符型特殊文件

    -b file

    检查file是否块设备文件

    #!/bin/bash
    
    device1="/dev/sda1"
    if [ -b "$device1" ]
    then
        echo "$device1 is a block device."
    fi
    
    device2='/dev/tty0'
    if [ -c "$device2" ]
    then
        echo "$device2 is a character device."
    fi
  • 相关阅读:
    返回一个首尾相连的整数数组中最大子数组的和
    《程序员修炼之道——从小工到专家》读后感一
    成功之路,贵在坚持
    有些路走下去会很苦很累,但是不走会后悔
    商品进行倒计时
    Hibernate中HQL函数汇总及获取当前时间进行比较举例
    java类的继承,多态,抽象类与接口
    equals()与 == 比较,hashCode方法
    面向对象基本知识
    命令控制台与java环境配置
  • 原文地址:https://www.cnblogs.com/wenwei-blog/p/13850394.html
Copyright © 2011-2022 走看看