zoukankan      html  css  js  c++  java
  • shell脚本学习(2)比较两个数字大小

      注意:shell中对比字符串只能使用==、<、>、!=、-z、-n。对比字符串时,末尾一定要加上x(或者a、b等)一个字符,因为if [ $1x == "ab"x ]时如果没有了x ,并且$1是"",这个语句会翻译成if [  == "ab" ],左边相当于没有东西了,会报语法错误。或者使用[[  ]],就不需要x了。使用<或者>时,如果是用[  ],需要用转义符"",如>。

        对比数字使用既能使用-eq、-ne、-gt、-ge、-lt、-le,也能使用==、<、>、!=。其中-eq的意思是equal,-ne是unequal,-gt是greater than,-ge是greater than or equal to,-lt是less than,-le是less than or equal to。

    [zhi@centos7 sh]$ cat number_compare.sh 
    #!/bin/bash
    #脚本名称:number_compare.sh
    #用途:比较二个数字大小
    echo " Please input first number:"
    read x
    echo  "you first number x=$x"
    read -p " Please input second number:" y
    echo  "you second number y=$y"
    
    if [ $x -eq $y ];then
        echo "equal"
    elif [ $x -gt $y ];then
        echo "x greater than y"
    else
        echo "x less than y"
    fi

    运行测试:

    [zhi@centos7 sh]$ ./number_compare.sh 
     Please input first number:
    34
    you first number x=34
     Please input second number:23
    you second number y=23
    x greater than y
    [zhi@centos7
    sh]$ ./number_compare.sh Please input first number: 22 you first number x=22 Please input second number:22 you second number y=22 equal
    [zhi@centos7
    sh]$ ./number_compare.sh Please input first number: 23 you first number x=23 Please input second number:56 you second number y=56 x less than y
  • 相关阅读:
    Redis常用数据类型及应用场景之Set
    Redis常用数据类型及应用场景之List
    Redis常用数据类型及应用场景之Hash
    exists & not exists
    oracle 中 dblink 的简单使用
    DockerCompose之数据卷Volume
    DockerCompose之常见编排脚本
    160308-学习State Pattern Actor
    12.3-框架维护
    12.2-机器人协作系统
  • 原文地址:https://www.cnblogs.com/me80/p/7989992.html
Copyright © 2011-2022 走看看