zoukankan      html  css  js  c++  java
  • shell脚本--逻辑判断与字符串比较

    涉及到比较和判断的时候,要注意

    1. 整数比较使用-lt,-gt,ge等比较运算符,详情参考:整数比较
    2. 文件测试使用 -d, -f, -x等运算发,详情参考:文件测试
    3. 逻辑判断使用    &&(且)、||(或)、!(取反)
    4. 字符串比较实用
    5. 字符串的比较使用以下三个比较运算符:= 或者(==)、!= 、> 、 <  、  
      1. -z表示后面的值是否为空,为空则返回true,否则返回false。
      2. -n表示判断后面的值是否为空,不为空则返回true,为空则返回false。

    下面的一个例子:

    #!/bin/bash
    #文件名:test.sh
    
    read -p 'please input name:' name
    read -p 'please input password:' pwd
    if [ -z $name ] || [ -z $pwd ]
    then 
        echo "hacker"
    else 
        if [ $name == 'root' ] && [ $pwd == 'admin' ]
        then 
            echo "welcome"
        else 
            echo "hacker"
        fi
    fi
    

      运行测试:

    ubuntu@ubuntu:~$ ./test.sh
    please input name:root
    please input password:admin
    welcome
    ubuntu@ubuntu:~$ ./test.sh
    please input name:root
    please input password:
    hacker
    ubuntu@ubuntu:~$ ./test.sh
    please input name:root 
    please input password:beyond
    hacker
    ubuntu@ubuntu:~$ 
    

    注意:  

      比较运算符的两边都有空格分隔,同时要注意比较运算符两边的变量是否可能为空,比如下面这个例子:

    #!/bin/bash
    #文件名:test.sh
    
    if [ $1 == 'hello' ];then 
        echo "yes"
    elif [ $1 == 'no' ];then 
        echo "no"
    fi
    

      运行:

    ubuntu@ubuntu:~$ ./test.sh
    ./test.sh: line 4: [: ==: unary operator expected
    ./test.sh: line 7: [: ==: unary operator expected
    ubuntu@ubuntu:~$ ./test.sh hello 
    yes
    ubuntu@ubuntu:~$ ./test.sh no
    no
    ubuntu@ubuntu:~$ ./test.sh test
    ubuntu@ubuntu:~$ 
    

      可以看到,在代码中想要判断shell命令的第二个参数是否为hello或者no,但是在测试的时候,如果没有第二个参数,那么就变成了 if [ == 'hello' ],这个命令肯定是错误的了,所以会报错,比较好的做法是在判断之前加一个判断变量是否为空  或者使用双引号将其括起来,注意,必须使用双引号,因为变量在双引号中才会被解析。

    #!/bin/bash
    #文件名:test.sh
    
    if [ "$1" == 'yes' ]; then
        echo "yes"
    elif [ "$1" == 'no' ]; then
        echo "no"
    else
        echo "nothing"
    fi
    

      运行:

    ubuntu@ubuntu:~$ ./test.sh
    nothing
    ubuntu@ubuntu:~$ ./test.sh yes
    yes
    ubuntu@ubuntu:~$ ./test.sh no
    no
    ubuntu@ubuntu:~$ ./test.sh demo
    nothing
    

      这样的话,就不会报错了。

      

  • 相关阅读:
    一篇文章搞明白CORS跨域
    我从来不理解JavaScript闭包,直到有人这样向我解释它...
    将博客搬至CSDN
    Spring Boot缓存源码分析
    网站技术架构
    在springboot中使用Mybatis Generator的两种方式
    官方文档Core Technologies
    Java诊断工具Arthas
    Intellij IDEA 修改代码后自动编译更新
    TabHost选项卡的实现(二):使用Fragment实现
  • 原文地址:https://www.cnblogs.com/-beyond/p/8262265.html
Copyright © 2011-2022 走看看