Shell Script的if else语句未按预期工作,求排查问题
Shell脚本if else密码判断始终返回正确的问题解决
你的代码核心问题是条件判断的语法错误:
在Shell的[ ](等同于test命令)中,比较操作符=的两边必须保留空格。你写的[ $pass="password" ]会被Shell解析成“检查字符串$passpassword是否非空”——不管你输入什么,这个拼接后的字符串都不会是空的,所以条件永远为真,自然每次都走正确分支。
另外,为了避免输入空值时出现语法错误,建议给变量加上双引号,修正后的代码如下:
#!/bin/bash clear echo "Enter password" read pass if [ "$pass" = "password" ] then echo "The password is correct." else echo "The password is incorrect, try again." fi
如果你用Bash的话,更推荐使用[[ ]]进行条件判断,它的语法更宽松,也不需要担心空值和空格的问题,写法如下:
#!/bin/bash clear echo "Enter password" read pass if [[ $pass == "password" ]] then echo "The password is correct." else echo "The password is incorrect, try again." fi
内容的提问来源于stack exchange,提问作者Linkachus 17
相关产品推荐
相关产品推荐

