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

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

  

原文地址:https://www.cnblogs.com/-beyond/p/8262265.html