99网
您的当前位置:首页shell脚本--逻辑判断与字符串比较

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

来源:99网
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:' nameread -p 'please input password:' pwdif [ -z $name ] || [ -z $pwd ]then

echo \"hacker\"else

if [ $name == 'root' ] && [ $pwd == 'admin' ] then

echo \"welcome\" else

echo \"hacker\" fifi

  运⾏测试:

ubuntu@ubuntu:~$ ./test.shplease input name:root

please input password:adminwelcome

ubuntu@ubuntu:~$ ./test.shplease input name:rootplease input password:hacker

ubuntu@ubuntu:~$ ./test.shplease input name:root

please input password:beyondhacker

ubuntu@ubuntu:~$

注意:  

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

#!/bin/bash

#⽂件名:test.shif [ $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 expectedubuntu@ubuntu:~$ ./test.sh hello yes

ubuntu@ubuntu:~$ ./test.sh nono

ubuntu@ubuntu:~$ ./test.sh testubuntu@ubuntu:~$

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

#!/bin/bash

#⽂件名:test.shif [ \"$1\" == 'yes' ]; then echo \"yes\"

elif [ \"$1\" == 'no' ]; then echo \"no\"else

echo \"nothing\"fi

  运⾏:

ubuntu@ubuntu:~$ ./test.shnothing

ubuntu@ubuntu:~$ ./test.sh yesyes

ubuntu@ubuntu:~$ ./test.sh nono

ubuntu@ubuntu:~$ ./test.sh demonothing

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

因篇幅问题不能全部显示,请点此查看更多更全内容