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

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

2023年8月2日发(作者:)

shell脚本⽐较字符串相等_shell脚本--逻辑判断与字符串⽐较涉及到⽐较和判断的时候,要注意整数⽐较使⽤-lt,-gt,ge等⽐较,详情参考:整数⽐较⽂件测试使⽤ -d, -f, -x等运算发,详情参考:⽂件测试逻辑判断使⽤ &&(且)、||(或)、!(取反)⽐较实⽤字符串的⽐较使⽤以下三个⽐较运算符:= 或者(==)、!= 、> 、-n表⽰判断后⾯的值是否为空,不为空则返回true,为空则返回false。下⾯的⼀个例⼦:#!/bin/bash#⽂件名: -p 'please input name:' nameread -p 'please input password:' pwdif [ -z $name ] || [ -z $pwd ]thenecho "hacker"elseif [ $name == 'root' ] && [ $pwd == 'admin' ]thenecho "welcome"elseecho "hacker"fifi运⾏测试:ubuntu@ubuntu:~$ ./se input name:rootplease input password:adminwelcomeubuntu@ubuntu:~$ ./se input name:rootplease input password:hackerubuntu@ubuntu:~$ ./se input name:rootplease input password:beyondhackerubuntu@ubuntu:~$注意:⽐较运算符的两边都有空格分隔,同时要注意⽐较运算符两边的变量是否可能为空,⽐如下⾯这个例⼦:#!/bin/bash#⽂件名: [ $1 == 'hello' ];thenecho "yes"elif [ $1 == 'no' ];thenecho "no"fi运⾏:ubuntu@ubuntu:~$ ././: line 4: [: ==: unary operator expected./: line 7: [: ==: unary operator expectedubuntu@ubuntu:~$ ./ helloyesubuntu@ubuntu:~$ ./ nonoubuntu@ubuntu:~$ ./ testubuntu@ubuntu:~$可以看到,在代码中想要判断shell命令的第⼆个参数是否为hello或者no,但是在测试的时候,如果没有第⼆个参数,那么就变成了 if [ =='hello' ],这个命令肯定是错误的了,所以会报错,⽐较好的做法是在判断之前加⼀个判断变量是否为空 或者使⽤双引号将其括起来,注意,必须使⽤双引号,因为变量在双引号中才会被解析。#!/bin/bash#⽂件名: [ "$1" == 'yes' ]; thenecho "yes"elif [ "$1" == 'no' ]; thenecho "no"elseecho "nothing"fi运⾏:ubuntu@ubuntu:~$ ./ingubuntu@ubuntu:~$ ./ yesyesubuntu@ubuntu:~$ ./ nonoubuntu@ubuntu:~$ ./ demonothing这样的话,就不会报错了。

发布者:admin,转转请注明出处:http://www.yc00.com/news/1690916897a462924.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信