您的位置:首页 > 运维架构 > Shell

shell脚本--逻辑判断与字符串比较

2018-01-11 00:06 288 查看
逻辑判断使用

  &&(且)、||(或)、!(取反)

字符串的比较不能使用前面的数值比较(-gt -lt -ge)等。

字符串的比较使用以下三个比较运算符:

==表示等于 ,左右两边的值相等时,返回true,否则返回false

!=表示不等于,左右两边的值不相等时,返回true,否则返回false

-z表示后面的值是否为空,为空则返回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' ],这个命令肯定是错误的了,所以会报错,比较好的做法是在判断之前加一个判断变量是否为空。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐